using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using VirtualTerminalControl;
using Action = System.Action;
using Font = System.Drawing.Font;
using Point = System.Drawing.Point;

namespace VirtualTerminalControl
{



    /// <summary>
    /// 虚拟终端控件
    /// </summary>
    public partial class VirtualTerminal : UserControl
    {

        #region  全局属性

        // 终端数据结构
        private readonly List<TerminalLine> _buffer = new List<TerminalLine>();
        /// <summary>
        /// 回显的的实例实例，用于实现自动换行
        /// </summary>
        private readonly List<LineInfo> _HistroylineInfo = new List<LineInfo>();

        /// <summary>
        /// 用于最后一行的TerminalLine编辑处理
        /// </summary>
        private List<LineInfo> _CulineInfo = new List<LineInfo>();


        private int _scrollOffset;
        private int _maxLines = int.MaxValue;
        /// <summary>
        /// 关键字颜色设置 表达式
        /// </summary>
        private ColorMatcher colorMatcher = new ColorMatcher();
        /// <summary>
        /// 取得终端的显示的行数
        /// </summary>
        public int Rows => _rows;
        public int Cols => _cols;

        // 选择功能
        private Selection _selection = new Selection();
        //  private Point _lastMousePos;

        // 渲染参数
        //private Font _font = new Font("Consolas", 12);
        private SizeF _charSize;
        private int _cols, _rows;
        private float CharWidth;
        private float CharHeight;
        private float CharCnWidth;

        /// <summary>
        /// 上一次刷新时间:
        /// </summary>
        private DateTime lastRefreshTime;

        /// <summary>
        /// 上一次刷新时间:
        /// </summary>
        private DateTime VscrolastRefreshTime;
        ///// <summary>
        ///// 刷新定时器
        ///// </summary>
        //private System.Timers.Timer refreshTimer;
        ///// <summary>
        ///// 刷新定时器
        ///// </summary>
        private System.Timers.Timer vscrollBarrefreshTimer;
        //private MyVScrollBar vscrollBar = null;

        /// <summary>
        /// 控件上次的宽度
        /// </summary>
        int LastWidth = 0;
        /// 控件上次的高度
        int LastHeight = 0;

        ///// <summary>
        ///// 滚动条更新状态
        ///// </summary>
        //bool ScrollBarUpdata = false;

        public static new Color DefaultBackColor { get; private set; }
        public static new Color DefaultForeColor { get; private set; }

        public static new Font DefaultFont { get; private set; }
        // 当前输入
        //private StringBuilder _currentInput = new StringBuilder();

        //  private Color _currentColor = Color.Black;

        #region  

        #endregion
        /// <summary>
        /// 是否处于最小化状态
        /// </summary>
        bool IsResize = false;


        /// <summary>
        ///背景颜色
        /// </summary>
        protected static SolidBrush back = new SolidBrush(Color.Black);
        // SolidBrush white = new SolidBrush(Color.FromArgb(3, 41, 81));
        static Color customGreen = Color.FromArgb(0, 255, 0);



        /// <summary>
        /// 字体颜色
        /// </summary>
      //  private SolidBrush white = new SolidBrush(Color.Lime);
        private SolidBrush white = new SolidBrush(customGreen);
        private StringFormat stringFormat = new StringFormat(StringFormatFlags.MeasureTrailingSpaces);

        // 浅红
        private readonly Color LightRed = Color.FromArgb(255, 248, 95, 56);
        // 紫色
        private readonly Color Purple = Color.FromArgb(255, 128, 0, 255);
        // 蓝色
        private readonly Color Blue = Color.FromArgb(255, 0, 128, 255);
        // 黄色
        private readonly Color Yellow = Color.FromArgb(255, 255, 128, 64);
        // 浅蓝青
        private readonly Color LightCyan = Color.FromArgb(255, 6, 255, 255);
        // 粉色
        private readonly Color Pink = Color.FromArgb(255, 255, 128, 255);

        /// <summary>
        /// 鼠标左键按下
        /// </summary>
        private bool IsMouseButtonsLeft = false;

        private DateTime LastMouseDown;

        /// <summary>
        /// 鼠标左键按下
        /// </summary>
        private bool IsAltDown = false;

        /// <summary>
        /// 鼠标左键按下
        /// </summary>
        private bool IsCtrlDown = false;

        /// <summary>
        /// 绘制的功能实例，测试用
        /// </summary>
        private Graphics graphics = null;


        /// <summary>
        /// 异步同步实例
        /// </summary>
        //  private SynchronizationContext syncContext = SynchronizationContext.Current;

        #endregion


        #region 滚动条更新

        // ScrollbarTime gundongtiaodelayTimer1 = null;
       // private System.Timers.Timer delayTimer; // 用于延迟处理的定时器
        #endregion


        #region  接受键盘输入事件

        //  BackgroundWorker backgroundWorker = new BackgroundWorker();
        /// <summary>
        ///  接受键盘输入委托
        /// </summary>
      //  public EventHandler<byte[]> KeyInputData;
        public delegate void DataRequest(byte[] data);

        /// <summary>
        /// 更新 行 与 列
        /// </summary>
        /// <param name="Rows"></param>
        /// <param name="Cols"></param>
        public delegate void DataResponse(int Rows, int Cols);
        /// <summary>
        /// 接受键盘输入
        /// </summary>
        public event DataRequest OnDataRequested;

        /// <summary>
        /// 更新 Rows 与 Cols
        /// </summary>
        public event DataResponse OnDataResponse;

        [DllImport("user32.dll")]
        private static extern bool SetProcessDpiAwarenessContext(int dpiFlag);


        private const int DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = -4;

        // 旧的DPI感知API (Windows 8.1及以下)
        [DllImport("shcore.dll")]
        private static extern int SetProcessDpiAwareness(ProcessDpiAwareness value);

        [DllImport("user32.dll")]
        private static extern bool SetProcessDPIAware();


        // 旧API的枚举
        private enum ProcessDpiAwareness
        {
            ProcessDpiUnaware = 0,
            ProcessSystemDpiAware = 1,
            ProcessPerMonitorDpiAware = 2
        }
        #endregion
        // 设置DPI感知



        private void SetDpiAwareness()
        {
            try
            {
                // 尝试使用最新的DPI感知API (Windows 10+)
                if (Environment.OSVersion.Version.Major >= 10)
                {
                    SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
                    bool result = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
                    if (!result)
                    {
                        // API调用失败，尝试旧方法
                        SetFallbackDpiAwareness();
                    }
                }
                else
                {
                    // 对于Windows 8.1及以下版本，使用旧API
                    SetFallbackDpiAwareness();
                }
            }
            catch (Exception ex)
            {
                // 记录错误或者使用默认DPI设置
                Console.WriteLine($"设置DPI感知时出错: {ex.Message}");
            }
        }

        private void SetFallbackDpiAwareness()
        {
            try
            {
                // 尝试使用Windows 8.1的API
                if (Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 3)
                {
                    SetProcessDpiAwareness(ProcessDpiAwareness.ProcessPerMonitorDpiAware);
                }
                else
                {
                    // 对于Windows 8及以下版本，使用较旧的API
                    SetProcessDPIAware();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"使用备用DPI感知方法时出错: {ex.Message}");
            }
        }
        public VirtualTerminal()
        {
            SetStyle(ControlStyles.OptimizedDoubleBuffer |
                    ControlStyles.AllPaintingInWmPaint | ControlStyles.UserMouse |
                        ControlStyles.UserPaint, true);

            ///设置动态感知dpi
            SetDpiAwareness();
            //      SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
            //   Console.WriteLine("初始化==》 开始");
            InitializeComponent();

            //delayTimer.Elapsed += DelayTimer_Elapsed;
            //refreshTimer.Elapsed += RefreshTimer_Elapsed;
            DefaultFont = this.Font;


            DefaultBackColor = this.BackColor;
            DefaultForeColor = this.ForeColor;
           // DefaultForeColor = Color.Green;

            //DefaultBackColor = Color.White;
            //DefaultForeColor = Color.Black;
            //    Console.WriteLine("初始化==》 完成");


            //    Console.WriteLine("字体 宽度等信息==》 开始");
            InitializeMetrics();
            //    Console.WriteLine("字体 宽度等信息==》 完成");
            ///设置滚动条
            ///
            //   Scroll += VirtualTerminal_Scroll;
            //   Console.WriteLine(Font.ToString());
        }




        public static SizeF GetCharSize(Font font, char c)
        {

            Size sz2 = TextRenderer.MeasureText("<" + c.ToString() + ">", font);
            Size sz3 = TextRenderer.MeasureText("<>", font);

            return new SizeF(sz2.Width - sz3.Width + 1, /*sz2.Height*/font.Height);
        }


        protected override void OnLoad(EventArgs e)
        {
            //Console.WriteLine("OnLoad  加载开始============================");
            //Console.WriteLine("设置滚动条==》 开始");
            InitializeScrollBars();
            //  Console.WriteLine("字体 宽度等信息==》 完成");
            InitializeContextMenu();

            Color red_c1 = Color.FromArgb(255, 255, 102, 102); //Color [A=255, R=255, G=102, B=102]
                                                               // this.colorMatcher.AddRule(@"drop|Disable|unassigned|Board|shutdown|down|DOWN|halt|disable|Error|\d{4}/\d{1,2}/\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}|((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)", red_c1);
            this.colorMatcher.AddRule(@"Invalid |drop|disabled|Disable|Board| shutdown| down| DOWN | DOWN|halt|disable|Error|offline|[7-9]\d(\.\d{0,3})?%", LightRed);
            this.colorMatcher.AddRule(@" patch|Patch |enable|router|router-id|system-id|interface |electric|input|neighbor|traffic-eng|area|routing|route|qinq|rule|bgp|OSPF|ISIS-L1|ISIS-L2|(ospf(v3)?)|( rip(ng)?)|eigrp|static|odr|unr|(is(\-)?is)|pim|direct |[4-6]\d(\.\d{0,3})?%", Color.Fuchsia); // Pink粉丝   
            this.colorMatcher.AddRule(@"^!.*>$|no shutdown|enable| (enable(d))?| permit |cleared |successful|[0-9a-fA-F]{4}[.-][0-9a-fA-F]{4}[.-][0-9a-fA-F]{4}| UP| UP| UP | up|up | up |\d{1,2}:\d{1,2}:\d{1,2}", Color.Lime);
            this.colorMatcher.AddRule(@"%[-\w\s]*%$|ipv6 address |ip address | unreachable| occurred |((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/\d{1,2}|%[a-zA-Z-]+%|[A-Z]{2}U-[0-9]+/[0-9]+/[0-9]+", LightCyan); //浅蓝青

            // this.colorMatcher.AddRule(@"router-id|system-id|interface|electric|input|neighbor|traffic-eng|area|routing|route|qinq|rule|", Color.Fuchsia ); // Pink粉丝                                                                                                                                                                                                                       // this.colorMatcher.AddRule(@"router-id|system-id|interface|electric|input|neighbor|traffic-eng|area|routing|route|qinq|rule|", Color.Fuchsia ); // Pink粉丝                                                                                                                                                                                                              // this.colorMatcher.AddRule(@"router-id|system-id|interface|electric|input|neighbor|traffic-eng|area|routing|route|qinq|rule|", Color.Fuchsia ); // Pink粉丝

            this.colorMatcher.AddRule(@"null1|deny|supervlan|prefix-pool|vlanpool|vlan|accounting|authentication|authorization|domain|cgn-pool}", Yellow); //浅黄色

            this.colorMatcher.AddRule(@"unassigned |mgmt_eth|xlgei-|xxvgei-|xlgei-|xgeiw-|xgeis-|xgeid-|smartgroup|[xlc]gei-|gei-|xgeiw-|orange|Ethernet|Eth|fast|(eth((\-)?(trunk)?))|null|loopback|tunnel|dialer|brief|serial|atm|pos|\s+(vlan|vlanif)\s*\d+", Color.Yellow);

            //  this.colorMatcher.AddRule(@"^!.*>$|no shutdown| (enable(d))?| |successful|[0-9a-fA-F]{4}[.-][0-9a-fA-F]{4}[.-][0-9a-fA-F]{4} | UP | up | up|\d{1,2}:\d{1,2}:\d{1,2}", Color.Lime);
            //this.colorMatcher.AddRule(@"drop|Disable|unassigned|Board|shutdown|down|DOWN|halt|disable|Error|\d{4}/\d{1,2}/\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}|((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)", red_c1);
            // this.colorMatcher.AddRule(@"router-id|system-id|interface|electric|input|neighbor|traffic-eng|area|routing|route|qinq|rule|", Color.Fuchsia ); // Pink粉丝
            // this.colorMatcher.AddRule(@"Destination|description||ipv6|ipv4|l2vpn|isis|ospfv2|ospv3|bgp|rip|ip|l2vpn", Blue); // 蓝色
            // this.colorMatcher.AddRule(@"null1|deny|supervlan|prefix-pool|vlanpool|vlan|accounting|authentication|authorization|domain|cgn-pool|Ethernet|Eth|\d{2}:\d{2}:\d{2}|^\d+\.\d+\.\d+$|FU-\d+(?:/\d+){2}", Yellow); //浅黄色

            // this.colorMatcher.AddRule(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/\d{1,2}|%[a-zA-Z-]+%|[A-Z]{2}U-[0-9]+/[0-9]+/[0-9]+", LightCyan); //浅蓝青

            // this.colorMatcher.AddRule(@"Serial|Uptime|destination", Purple); // 紫色 Purple
            // this.colorMatcher.AddRule(@"smartgroup|Patch-|Base-|Bras-|[a-zA-Z]+-\d+\/\d+\/\d+\/\d+|(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]) (0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])-(19|20)\d{2}| ((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]  |[01]?[0-9][0-9]?)", Color.Yellow);

            // this.colorMatcher.AddRule(@"show", Color.Yellow);
            //this.colorMatcher.AddRule(@"(dis((able(d)?)|(connect(ed)?)|(allow(ed)?)|(card(ed)?))|(error(s)?))|(fail((ure)|(ed))?)|((city)?[w]{2}m)|(den((y)|(ied)){1})", Color.Red);
            //this.colorMatcher.AddRule(@"red|administratively|undo|unknown|fault|block|refused|problem|warnings|alerts|critical|delete|inactive|unassigned|error|board", Color.Red);
            //this.colorMatcher.AddRule(@"(([7-9]\d)|(100))(\.\d{0,3})?\%", Color.Red);
            //this.colorMatcher.AddRule(@"green|up|forward|full|active", Color.Red);

            //this.colorMatcher.AddRule(@"(connect(ed)?)|(permit(ed)?)|(estab(lish)?(ed)?)|(enable(d)?|(allow(ed)?))", Color.Red);
            //this.colorMatcher.AddRule(@"(([0-3](\d)?)|\d{1})(\.\d{0,2})?\%", Color.Red);
            //this.colorMatcher.AddRule(@"(bgp|(ospf(v3)?)|(rip(ng)?)|eigrp|static|odr|unr|(is(\-)?is)|pim|direct)(\-\d*)?", Color.Red);
            //this.colorMatcher.AddRule(@"cyan|ipv6|tcp|udp|(i(c|g)mp)|gre|esp|ah|isakmp|(arp(a)?)|dhcp|(http(s)?)|dns|((t)?ftp)|telnet|ssh|www|ntp|radius|tacacs|pop\d|smtp|ppp|fr(ame(\-)?relay)?|hdlc", Color.Red);
            //this.colorMatcher.AddRule(@"standby|vrrp|glbp|(mst(p)?)|((r)?stp)|spanning\-tree|dot1q|802\.1q", Color.Red);
            //this.colorMatcher.AddRule(@"ldp|tdp|mpls|aaa|(account(ing)?)|(auth((entication)|(orization)))|nat|bfd|nqa|sla|rtr|vrf|vpn(\-instance)?", Color.Red);
            //this.colorMatcher.AddRule(@"(((passive\-)|(silent\-))?interface)|(in|out)((bound)|(put))?", Color.Red);
            //this.colorMatcher.AddRule(@"magenta|router|redistribute|(import(\-route)?)|export|network|neighbor|peer|area|acl|(class((ifier)|(\-map)))|behavior|policy(\-map)?", Color.Red);
            //this.colorMatcher.AddRule(@"access\-((list)|(class)|(group))|ip\-prefix|prefix\-list|(route(\-.*)?)|(traffic.*)", Color.Red);
            //this.colorMatcher.AddRule(@"[4-6]\d((\.\d{0,3})?)\%", Color.Red);
            //this.colorMatcher.AddRule(@"((fast)?|(gigabit)?)ethernet((\d)?\d\/)*(\d)+(\.\d{1,4})?", Color.Red);
            //this.colorMatcher.AddRule(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(\/(\d){0,2})?", Color.YellowGreen);

            //this.colorMatcher.AddRule(@"([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4}(\/(\d){0,3})?", Color.Red);
            //this.colorMatcher.AddRule(@"([0-9a-fa-f]{4}[.|-][0-9a-fa-f]{4}[.|-][0-9a-fa-f]{4})|([0-9a-fa-f]{2}[.|-]){5}[0-9a-fa-f]{2}", Color.Red);
            //this.colorMatcher.AddRule(@"\d{1,2}\.([0-9a-fA-F]{2,4}.){1,11}\d{1,2}", Color.Red);
            //this.colorMatcher.AddRule(@"(xgeiw|smartgroup|[xlc]gei|gei|xgeiw|orange|ge|fa|fe|(eth((\-)?(trunk)?))|null|loopback|tunnel|dialer|bri|serial|atm|pos|(vlan(if)?))(((\d)?\d\/)*(\d)+)?", Color.Yellow);
            //this.colorMatcher.AddRule(@"(xlgei|cgei|xgei|xgeiw|gei|smartgroup|(eth((\-)?(trunk)?))null|loopback|tunnel|dialer|bri|serial|atm|pos|(vlan(if)?))(((\d)?\d\/)*(\d)+)?", Color.Red);
            //  this.colorMatcher.AddRule(@"(xgeiw|smartgrou|[xlc]gei|gei|xgeiw|orange|ge|fa|fe|(eth((\-)?(trunk)?))|null|loopback|tunnel|dialer|bri|serial|atm|pos|(vlan(if)?))(((\d)?\d\/)*(\d)+)?", Color.Red);


            //   Console.WriteLine("OnLoad 加载完成============================");
            base.OnLoad(e);
        }

        #region 初始化逻辑

        private void DelayTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            // 当延迟时间到了（即最后一次窗口大小变化后经过了设定的延迟时间）
            if (this.Width == 0 || this.Height == 0)
            {
                Console.WriteLine("OnResize" + " = 0");
            }
            else if (this.Width < 0 || this.Height < 0)
            {
                Console.WriteLine("OnResize" + " < 0");
            }
            //else if (LastHeight == 0 && LastWidth == 0)
            //{
            //    LastWidth = this.Width;
            //    LastHeight = this.Height;
            //    TriggerRefresh();
            //}
            else if (LastWidth != this.Width || LastHeight != Height)
            {
                _selection.IsValid = false;
                LastWidth = this.Width;
                LastHeight = this.Height;
                InitializeMetrics();

                //string escapeSequence = $"\x1b[8;{_rows};{_cols}t";
                //OnDataRequested?.Invoke(Encoding.ASCII.GetBytes(escapeSequence));
                // OnDataRequested?.(Encoding.ASCII.GetBytes(escapeSequence));
                //    OnDataResponse?.Invoke(_rows,_cols);
                IsResize = false;
                // Invalidate();
                TriggerRefresh();
            }
            else
            {
                //  Console.WriteLine("重新加载");
                IsResize = false;
                // this.Invalidate();
                TriggerRefresh();

            }
        }
        private void RefreshTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            // 触发更新
            //Console.WriteLine(" 触发更新");

            // TriggerRefresh();
            refreshTimer.Stop();
            PerformRefresh();
            //    Console.WriteLine("RefreshTimer_Elapsed==> lastRefreshTime: " + lastRefreshTime.ToString("yyyy-MM-dd HH:mm:ss:ffff") + "  "+ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + "Nows RefreshTimer_Elapsed:");
        }


        private static object LockTime = new object();
        /// <summary>
        /// 即使刷新方法
        /// </summary>
        private void PerformRefresh()
        {
            // 记录本次刷新时间
            lock (LockTime)
            {
                lastRefreshTime = DateTime.Now;
            }

            // 调用 Invalidate 方法刷新控件
            //      Console.WriteLine("触发更新： PerformRefresh ==> lastRefreshTime: " + lastRefreshTime.ToString("yyyy-MM-dd HH:mm:ss:ffff") + "  " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + "Nows RefreshTimer_Elapsed:");
            this.Invalidate();
        }


        /// <summary>
        /// 延迟刷新的方法
        /// </summary>
        private void TriggerRefresh()
        {
            //  refreshTimer.AutoReset = false; ;
            // refreshTimer.Enabled = true;
            DateTime currentTime = DateTime.Now;
            TimeSpan elapsedTime = new TimeSpan();
            lock (LockTime)
            {

                elapsedTime = currentTime - lastRefreshTime;
                //lastRefreshTime = DateTime.Now;
            }

            //     Console.WriteLine($"{elapsedTime.TotalMilliseconds}  {currentTime.ToString("mm:ss fffff")} {lastRefreshTime.ToString("mm:ss fffff")} ");
            if (elapsedTime.TotalMilliseconds >= 30)
            {
                // 间隔大于等于 50 毫秒，直接刷新
                // refreshTimer.Stop();
                PerformRefresh();
            }
            else
            {
                // 间隔小于 50 毫秒，设置定时器延迟到 50 毫秒后刷新
                try
                {
                    if (refreshTimer.Enabled)
                    {
                        refreshTimer.Stop();
                        refreshTimer.Start();
                    }
                    else
                    {
                        refreshTimer.Start();

                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                if (!refreshTimer.Enabled)
                {

                    refreshTimer.Enabled = true;
                }



            }



        }

        private static object LockTime_Vscro = new object();


        private void VscroPerformRefresh()
        {
            vscrollBarrefreshTimer.Stop();
            // 记录本次刷新时间
            lock (LockTime_Vscro)
            {
                VscrolastRefreshTime = DateTime.Now;
            }

            // 调用 Invalidate 方法刷新控件
            //      Console.WriteLine("触发更新： PerformRefresh ==> lastRefreshTime: " + lastRefreshTime.ToString("yyyy-MM-dd HH:mm:ss:ffff") + "  " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + "Nows RefreshTimer_Elapsed:");
            //   this.Invalidate();
            UpdateScrollBars();
        }

        /// <summary>
        /// 滚动条刷新方法
        /// </summary>
        private void TriggerVscroPerformRefresh()
        {


            DateTime currentTime = DateTime.Now;
            TimeSpan elapsedTime = new TimeSpan();
            lock (LockTime)
            {

                elapsedTime = currentTime - VscrolastRefreshTime;

            }

            if (elapsedTime.TotalMilliseconds >= 100)
            {
                // 间隔大于等于 50 毫秒，直接刷新
                // refreshTimer.Stop();
                VscroPerformRefresh();
            }
            else
            {
                // 间隔小于 50 毫秒，设置定时器延迟到 50 毫秒后刷新
                try
                {
                    if (vscrollBarrefreshTimer.Enabled)
                    {
                        vscrollBarrefreshTimer.Stop();
                        vscrollBarrefreshTimer.Start();
                    }
                    else
                    {
                        vscrollBarrefreshTimer.Start();

                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                if (!vscrollBarrefreshTimer.Enabled)
                {

                    vscrollBarrefreshTimer.Enabled = true;
                }



            }


        }



        /// <summary>
        /// 滚动条更新数值方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gudongtiaodelayTimer1_Elapsed(object sender, ElapsedEventArgs e)
        {
            VscroPerformRefresh();





        }

        /// <summary>
        /// 缩放比例
        /// </summary>
        double zoom = 1.0;
        //  float zoom = 1.0f;
        /// <summary>
        /// 初始化字体 与 宽度等信息
        /// </summary>
        private void InitializeMetrics(double zoom = 1.0f)
        {

            //  SizeF sizeF1 = GetCharSizeF(this.Font,this.Width);
            // SizeF sizeF = GetCharSize(this.Font, 'W');
            if (zoom != 1.0f)
            {
                this.Font = new System.Drawing.Font(Font.Name, DefaultFont.Size * (float)zoom, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            }
            SizeF sizeF1 = GetCharSize(this.Font, '.');
            //if (sizeF1.Width == sizeF.Width)
            //{
            //    Console.WriteLine("等宽字体" + this.Font.ToString());
            //    //    this.ForeColor = Color.Red;
            //    Console.WriteLine(sizeF1.Width + "  " + sizeF1.Height);
            //}
            CharWidth = sizeF1.Width;
            CharHeight = sizeF1.Height; //高度显示重叠问题，分析与dpi 缩放有一定关系，最好感知dip 缩放，能有效提升小时效果
            this.CharCnWidth = sizeF1.Width * 2;
            //int CharWidth1 = (int)Math.Round(sizeF.Width * 1f /*0.85*/) - 1 /*0*/;
            //int CharCRnWidth1 = (int)Math.Round(GetCharSize(this.Font, '中').Width * 1f /*0.85*/) /*0*/;
            //int CharHeight1 = (int)Math.Round(sizeF.Height * 1f /*0.9*/) - 1 /*0*/;

            _charSize = sizeF1;
            //using (var g = CreateGraphics())
            //    {
            //        _charSize = TextRenderer.MeasureText(g, "W", _font);
            //    }
            int last_cols = _cols;
            int last_rows = _rows;
            _cols = (ClientSize.Width - this.vscrollBar.Width) / (int)_charSize.Width;
          //  _rows = ClientSize.Height / (int)_charSize.Height;
            _rows = ClientSize.Height / (int)CharHeight;
            if ((last_rows == 0 || _rows == 0))
            {
                return;
            }

            if (last_rows != _rows && last_cols != _cols)    //长度与宽度都发生了变化：
            {

                ///变换前的屏幕的第一行 索引
                var lastStartLineNum = _scrollOffset / CharHeight;
                int LastHistroylineInfoCount = _HistroylineInfo.Count;
                //取得最后一条上一次 TerminalLine 

                if (lastStartLineNum + last_rows < _HistroylineInfo.Count)
                {
                    ///缓存变化前的 数据总数

                    ///变换前的屏幕的最后行 
                    LineInfo lastlineinfo = _HistroylineInfo[(int)lastStartLineNum + last_rows - 1];

                    //变换前的屏幕的最后一行
                    //      LineInfo lastlineinfo = _HistroylineInfo[last_end_num];

                    UpdataLineInfoALl(_cols);
                    ///取得变化后的数据行数
                    int CuLineNum = _HistroylineInfo.Count;


                    if (CuLineNum == LastHistroylineInfoCount)
                    {
                        //    Console.WriteLine("无变化");
                        ///无变化
                        return;
                    }
                    //   Console.WriteLine("有变化");
                    ///二叉树方式查找最后一行，在新的中的索引
                    int index = _HistroylineInfo.BinarySearch(lastlineinfo);
                    while (_HistroylineInfo.Count > index)
                    {
                        if (_HistroylineInfo[index].LineIndex == _HistroylineInfo[index + 1].LineIndex)
                        {
                            index++;

                        }
                        else
                        {
                            break;
                        }
                    }
                    var teno = _HistroylineInfo[index];

                    if (index >= 0)
                    {

                        ///正常情况应该一定存在， 则计算出 第一行的索引 ，继而算出 _scrollOffset
                        /// 


                        //  _scrollOffset =  Math.Max(0, (index - _rows+1) * (int)CharHeight);
                        _scrollOffset = Math.Max(0, (index - _rows + 2) * (int)CharHeight);
                        if (CuLineNum > LastHistroylineInfoCount)
                        {

                            ///说明 宽度缩小了
                            this.vscrollBar.Maximum = this.Count;
                            UpdateScrollBars();

                        }
                        else
                        {
                            ///说明 宽度放大了

                            UpdateScrollBars();
                            this.vscrollBar.Maximum = this.Count;
                        }




                        //if (_CulineInfo.Count)
                        //  Console.WriteLine($"使用自定义比较器找到元素 {_HistroylineInfo[index]}，索引为 {index}");
                    }

                    else
                    {
                        Console.WriteLine("异常没有查找到");
                    }

                }
                else
                {
                    UpdataLineInfoALl(_cols);
                    int CuLineNum = _HistroylineInfo.Count;

                    if (CuLineNum == LastHistroylineInfoCount)
                    {
                        _scrollOffset = Math.Max(0, (this.Count - _rows) * (int)CharHeight);
                        UpdateScrollBars();
                        return;
                    }
                    if (CuLineNum > LastHistroylineInfoCount)
                    {

                        ///说明 宽度缩小了
                        ///
                        _scrollOffset = Math.Max(0, (this.Count - _rows) * (int)CharHeight);
                        this.vscrollBar.Maximum = this.Count;
                        UpdateScrollBars();

                    }
                    else
                    {
                        ///说明 宽度放大了
                        _scrollOffset = Math.Max(0, (this.Count - _rows) * (int)CharHeight);
                        UpdateScrollBars();
                        this.vscrollBar.Maximum = this.Count;
                    }
                    // UpdateScrollBars();
                    //焦点在最后一行
                    //  int last_max_rows = _CulineInfo[(int)lastStartLineNum].LineIndex;
                }









            }
            else if (last_cols != _cols)
            {                ///变换前的屏幕的第一行 索引
                var lastStartLineNum = _scrollOffset / CharHeight;

                //取得最后一条上一次 TerminalLine 
                ///缓存变化前的 数据总数
                int LastHistroylineInfoCount = _HistroylineInfo.Count;
                if (lastStartLineNum + last_rows < _HistroylineInfo.Count)
                {

                    ///变换前的屏幕的最后行 
                    LineInfo lastlineinfo = _HistroylineInfo[(int)lastStartLineNum + last_rows - 1];

                    //变换前的屏幕的最后一行
                    //      LineInfo lastlineinfo = _HistroylineInfo[last_end_num];

                    UpdataLineInfoALl(_cols);
                    ///取得变化后的数据行数
                    int CuLineNum = _HistroylineInfo.Count;


                    if (CuLineNum == LastHistroylineInfoCount)
                    {
                        ///无变化
                        return;
                    }

                    ///二叉树方式查找最后一行，在新的中的索引
                    int index = _HistroylineInfo.BinarySearch(lastlineinfo);
                    while (_HistroylineInfo.Count > index)
                    {
                        if (_HistroylineInfo[index].LineIndex == _HistroylineInfo[index + 1].LineIndex)
                        {
                            index++;

                        }
                        else
                        {
                            break;
                        }
                    }
                    var teno = _HistroylineInfo[index];

                    if (index >= 0)
                    {

                        ///正常情况应该一定存在， 则计算出 第一行的索引 ，继而算出 _scrollOffset
                        /// 


                        _scrollOffset = Math.Max(0, (index - _rows + 1) * (int)CharHeight);

                        if (CuLineNum > LastHistroylineInfoCount)
                        {

                            ///说明 宽度缩小了
                            this.vscrollBar.Maximum = this.Count;
                            UpdateScrollBars();

                        }
                        else
                        {
                            ///说明 宽度放大了

                            UpdateScrollBars();
                            this.vscrollBar.Maximum = this.Count;
                        }




                        //if (_CulineInfo.Count)
                        //  Console.WriteLine($"使用自定义比较器找到元素 {_HistroylineInfo[index]}，索引为 {index}");
                    }

                    //else
                    //{
                    //   // Console.WriteLine("异常没有查找到");
                    //}

                }
                else
                {
                    UpdataLineInfoALl(_cols);
                    int CuLineNum = _HistroylineInfo.Count;

                    if (CuLineNum == LastHistroylineInfoCount)
                    {
                        return;
                    }
                    if (CuLineNum > LastHistroylineInfoCount)
                    {

                        ///说明 宽度缩小了
                        ///
                        _scrollOffset = Math.Max(0, (this.Count - _rows) * (int)CharHeight);
                        this.vscrollBar.Maximum = this.Count;
                        UpdateScrollBars();

                    }
                    else
                    {
                        ///说明 宽度放大了
                        _scrollOffset = Math.Max(0, (this.Count - _rows) * (int)CharHeight);
                        UpdateScrollBars();
                        this.vscrollBar.Maximum = this.Count;
                    }
                    //焦点在最后一行
                    //  int last_max_rows = _CulineInfo[(int)lastStartLineNum].LineIndex;
                }
                //Stopwatch stopwatch = new Stopwatch();
                //stopwatch.Start(); // 开始计时
                //UpdataLineInfoALl(_cols);
                //stopwatch.Stop(); // 停止计时
                //TimeSpan elapsedTime = stopwatch.Elapsed; // 获取经过的时间
                //Console.WriteLine($"  Count: {_buffer.Count}  Useing Time:  {elapsedTime.TotalMilliseconds}  _HistroylineInfo: {_HistroylineInfo.Count} 每秒回显的行数： {_buffer.Count / elapsedTime.TotalSeconds}");
                ////只有宽度发生了变化

            }
            else if (last_rows != _rows)
            {
                //只有行发生了变化

                if (_rows >= _HistroylineInfo.Count)
                {
                    _scrollOffset = 0;
                    UpdateScrollBars();
                    return;
                }


                //差值
                int chazhi = 0;
                if ((chazhi = _rows - last_rows) > 0)
                {
                    //可显示区域变大
                    //   Console.WriteLine(" Old :_scrollOffset" + _scrollOffset);
                    _scrollOffset = Math.Max(0, _scrollOffset -= (int)(chazhi * CharHeight));
                    UpdateScrollBars(_scrollOffset);
                    //   Console.WriteLine("New :_scrollOffset" + _scrollOffset);
                }
                else if (last_rows >= _HistroylineInfo.Count && _rows < _HistroylineInfo.Count)
                {
                    ///可现实区域缩小了
                    /// 有2钟情况:
                    /// 1. 原来时的 一个 屏幕就可以显示 ,当前一个屏幕显示不下
                    /// 2. 原来时的 一个 屏幕就可以显示不下 ,当前一个屏幕也显示不下
                    /// 需要考虑 当前 数据总的一个关系；


                    //可显示区域变小
                    //应该与更新的数

                    _scrollOffset = (_HistroylineInfo.Count - _rows) * (int)CharHeight;
                    UpdateScrollBars(_scrollOffset);

                }
                else
                {
                    chazhi = last_rows - _rows;
                    //   Console.WriteLine(" Old :_scrollOffset" + _scrollOffset);
                    _scrollOffset = Math.Max(0, _scrollOffset += (int)(chazhi * CharHeight));
                    UpdateScrollBars(_scrollOffset);
                    // Console.WriteLine("New :_scrollOffset" + _scrollOffset);
                }

            }

            return;


        }

        private static object LocketUpdata = new object();

        /// <summary>
        /// 更新 LineInfo 列表
        /// </summary>
        /// <param name="Cols"></param>
        private void UpdataLineInfoALl(int Cols)
        {
            if (_buffer.Count == 0)
            {
                return;
            }
            lock (LocketUpdata)
            {
                _HistroylineInfo.Clear();
                for (int i = 0; i < _buffer.Count - 1; i++)
                {
                    ///更新对应的索引方便 反向查找
                    _buffer[i].HistroyLineInfoStartIndex = _HistroylineInfo.Count;

                    _HistroylineInfo.AddRange(_buffer[i].GetCuLineInfo(i, Cols));
                }
            }
            _CulineInfo = _buffer.Last().GetCuLineInfo(_buffer.Count - 1, Cols);

        }

        /// <summary>
        /// 滚动条参数设置
        /// </summary>
        private void InitializeScrollBars()
        {
            vscrollBar.Dock = DockStyle.Right;
            vscrollBar.Width = 24;
            this.Controls.Add(vscrollBar);
            vscrollBar.Maximum = 1;
            vscrollBar.Minimum = 0;
            vscrollBar.Scroll += ScrollBar_Scroll;
            vscrollBarrefreshTimer = new System.Timers.Timer(100);
            vscrollBarrefreshTimer.Enabled = false;
            vscrollBarrefreshTimer.AutoReset = false; // 只执行一次，定时器到时后不自动重启
            vscrollBarrefreshTimer.Elapsed += gudongtiaodelayTimer1_Elapsed;
            NewLine();
            // vscrollBar.KeyPress += VscrollBar_KeyPress;
            UpdateScrollBars();





        }

        //private void VscrollBar_KeyPress(object sender, KeyPressEventArgs e)
        //{

        //    e.Handled = true;
        //}

        private void ScrollBar_Scroll(object sender, ScrollEventArgs se)
        {
            //逻辑 固定逻辑
            //Value + LargeChange - 1 = Max

            // 继而推到  Value 与 _scrollOffset的逻辑应该为  _scrollOffset = Value-1

            _scrollOffset = (int)Math.Max(0, this.vscrollBar.Value - 1) * (int)CharHeight;
            //  Console.WriteLine(vscrollBar.ToString() + " _rows: " + _rows + " _scrollOffset: " + _scrollOffset / CharHeight);
            TriggerRefresh();
            // Invalidate();

        }



        //}
        /// <summary>
        /// 更新滚动条的相关信息,更新到最新的值
        /// </summary>
        private void UpdateScrollBars()
        {

            this.vscrollBar.BeginInvoke(new Action(() =>
            {
                this.vscrollBar.SuspendLayout(); // 暂停布局更新
                var culinenum = (int)(_scrollOffset / CharHeight) + 1;
                this.vscrollBar.Maximum = Count;
                if (this.vscrollBar.LargeChange != _rows)
                {
                    this.vscrollBar.LargeChange = _rows;
                    this.vscrollBar.SetValue(culinenum);
                }

                if (Count > _rows)
                {
                    _scrollOffset = (LastSum - _rows) * (int)CharHeight;
                    this.vscrollBar.SetValue(culinenum);


                    //   UpdateScrollBars(_scrollOffset);
                    //_scrollOffset += (int)CharHeight;
                    // _scrollOffset = (int)Math.Max(0, this.vscrollBar.Maximum - _rows + 1) * (int)CharHeight;
                }
                this.vscrollBar.ResumeLayout(); // 恢复布局更新并强制立即更新
                // 这里放置需要在 UI 线程上执行的代码
            }));

            //if (this.vscrollBar.InvokeRequired)
            //{
            //    this.vscrollBar.BeginInvoke(new Action(() =>
            //    {
            //        this.vscrollBar.LargeChange = _rows;
            //        //this.vscrollBar.Value = (int)(_scrollOffset / CharHeight)+1;
            //        this.vscrollBar.SetValue((int)(_scrollOffset / CharHeight) + 1);
            //    }));
            //}
            //else
            //{

            //    this.vscrollBar.LargeChange = _rows;
            //    //   this.vscrollBar.Value = (int)(_scrollOffset / CharHeight)+1;
            //    this.vscrollBar.SetValue((int)(_scrollOffset / CharHeight) + 1);
            //}
        }
        /// <summary>
        /// 更新值滚动条当前值
        /// </summary>
        /// <param name="_scrollOffset"></param>
        private void UpdateScrollBars(int _scrollOffset)
        {
            InvokeIfRequired(() =>
            {
                try
                {
                    //   this.vscrollBar.Value = ((int)(_scrollOffset / CharHeight) + 1);
                    this.vscrollBar.SetValue((int)(_scrollOffset / CharHeight) + 1);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("UpdateScrollBars==> " + ex.StackTrace + "\r\n" + ex.Message);
                }


            });


        }

        /// <summary>
        /// 委托方法
        /// </summary>
        /// <param name="action"></param>
        private void InvokeIfRequired(Action action)
        {
            if (this.vscrollBar.InvokeRequired)
            {
                this.vscrollBar.BeginInvoke(action);
            }
            else
            {
                action();
            }
        }

        /// <summary>
        /// 右键菜单设置 测试
        /// </summary>
        private void InitializeContextMenu()
        {
            //var menu = new ContextMenuStrip();
            //var copyItem = new ToolStripMenuItem("复制", null, (s, e) => CopySelection());
            //menu.Items.Add(copyItem);
            //menu.Items.Add(copyItem);
            //ContextMenuStrip = menu;
        }
        #endregion

        #region 核心渲染逻辑
        protected void OnPaint_bak(PaintEventArgs e)
        {
            if (IsResize)
            {
                return;
            }
            base.OnPaint(e);
            e.Graphics.Clear(DefaultBackColor);
            //     e.Graphics.Clear(base.BackColor);

            var g = e.Graphics;
            //  g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //// 设置高质量的合成质量
            //  g.CompositingQuality = CompositingQuality.HighQuality;
            //// 设置高质量的文本渲染提示
            // g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            // 计算可见区域
         //   int startLine = _scrollOffset / (int)_charSize.Height;
            int startLine = _scrollOffset / (int)CharHeight;
            if (startLine < 0)
            {
                return;
                throw new DivideByZeroException("_scrollOffset 未负数");
            }
            int endLine = Math.Min(startLine + _rows + 1, _buffer.Count);
            // Console.WriteLine($"StartLine : {startLine}  endLine: {endLine}");
            for (int i = startLine; i < endLine; i++)
            {

              //  int yPos = i * (int)_charSize.Height - _scrollOffset;
                int yPos = i * (int)CharHeight - _scrollOffset;
                //  Console.WriteLine("GetNextCharRectangleF==> yPos: " + yPos);
                DrawLine(g, _HistroylineInfo[startLine], yPos);
                //DrawLine(g, _buffer[i], yPos);
            }

            ///存在选中区域
            if (_selection.IsValid)
            {
                DrawSelection(g);
            }

        }

        protected override void OnPaint(PaintEventArgs e)
        {
            if (IsResize)
            {
                return;
            }
            base.OnPaint(e);
            e.Graphics.Clear(DefaultBackColor);
            //     e.Graphics.Clear(base.BackColor);

            var g = e.Graphics;
            //  g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //// 设置高质量的合成质量
            //  g.CompositingQuality = CompositingQuality.HighQuality;
            //// 设置高质量的文本渲染提示
            // g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            // 计算可见区域
   //         int startLine = _scrollOffset / (int)_charSize.Height;
            int startLine = _scrollOffset / (int)CharHeight;
            if (startLine < 0)
            {
                return;
                throw new DivideByZeroException("_scrollOffset 为负数");
            }
            int endLine = Math.Min(startLine + _rows, this.Count);
            // Console.WriteLine($"StartLine : {startLine}  endLine: {endLine}");
            //  LineInfo TempLine = null;
            for (int line = startLine; line < endLine; line++)
            {

              //  int yPos = line * (int)_charSize.Height - _scrollOffset;
                int yPos = line * (int)CharHeight - _scrollOffset;
                //  Console.WriteLine("GetNextCharRectangleF==> yPos: " + yPos);

                if (line < _HistroylineInfo.Count)
                {
                    DrawLine(g, _HistroylineInfo[line], yPos);
                }
                else
                {
                    DrawLine(g, _CulineInfo[line - _HistroylineInfo.Count], yPos);
                }

                // DrawLine(g, _HistroylineInfo[line], yPos);
            }

            ///存在选中区域
            if (_selection.IsValid)
            {
                DrawSelection(g);
            }



        }
        private void DrawLine(Graphics g, LineInfo line, int yPos)
        {
            DrawLine(g, _buffer[line.LineIndex], line.Start, line.End, yPos);
            //if (line.IsCursor)
            //{
            //    using (var brush = new SolidBrush(Color.FromArgb(100, 255, 255, 250)))
            //    {
            //        //line.GetStartOffsetIndex(line.Index)

            //        g.FillRectangle(brush, line.Index * CharWidth + 3, yPos, CharWidth, CharHeight);
            //    }
            //}



        }

        private void DrawLine(Graphics g, TerminalLine line, int Start, int End, int yPos)
        {
            if (line == null)
            {
                return;
            }
            float xPos = 0;

            var segment = line.GetSegments();
            //  Console.WriteLine($"DrawLine: line: Start: {Start}  End: {End}  yPos: {yPos} ");
            for (int i = Start; i < End; i++)
            {

                if (segment[i].CharColor == DefaultBackColor)
                {
                    g.DrawString(segment[i].Char.ToString(), this.Font, new SolidBrush(DefaultBackColor), xPos, yPos, stringFormat);
                }
                else
                {

                    g.DrawString(segment[i].Char.ToString(), this.Font, new SolidBrush(segment[i].CharColor), xPos, yPos, stringFormat);
                }
                if (IsChinese(segment[i].Char))
                {
                    xPos += CharCnWidth;
                }
                else
                {
                    xPos += CharWidth;

                }
            }

            //foreach (var segment in line.GetSegments())
            //{
            //    if (segment.CharColor == DefaultBackColor)
            //    {
            //        g.DrawString(segment.Char.ToString(), this.Font, new SolidBrush(DefaultBackColor), xPos, yPos, stringFormat);
            //    }
            //    else
            //    {
            //        g.DrawString(segment.Char.ToString(), this.Font, new SolidBrush(segment.CharColor), xPos, yPos, stringFormat);
            //    }
            //    if (IsChinese(segment.Char))
            //    {
            //        xPos += CharCnWidth;
            //    }
            //    else
            //    {
            //        xPos += CharWidth;

            //    }
            //    //  xPos += CharWidth;

            //}

            //if (line.IsCursor)
            //{
            //    Console.WriteLine();
            //}
            if (line.IsCursor && (line.Index >= Start && line.Index <= End))
            {
                using (var brush = new SolidBrush(Color.FromArgb(100, 255, 255, 250)))
                {
                    //line.GetStartOffsetIndex(line.Index)

                    g.FillRectangle(brush, line.GetStartOffsetIndex(Start, line.Index) * CharWidth + 3, yPos, CharWidth, CharHeight);
                }
            }

        }

        /// <summary>
        /// 判断是否为中文字符
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        private static bool IsChinese(char? c)
        {
            if (c == null)
            {
                return false;
            }
            else
            {
                return c >= '\u4E00' && c <= '\u9FFF';
            }
            // 判断字符是否在常见中文字符的 Unicode 编码范围内

        }

        /// <summary>
        /// 绘制选中效果
        /// </summary>
        /// <param name="g"></param>
        private void DrawSelection(Graphics g)
        {
            if (!_selection.IsValid)
                return;


            var rects = CalculateSelectionRects();
            //   Console.WriteLine("CalculateSelectionRects:===> " + rects.Count);
            using (var brush = new SolidBrush(Color.FromArgb(150, 230, 230, 250)))
            {
                // Console.WriteLine(DefaultBackColor);




                rects.ForEach(r => g.FillRectangle(brush, r));
            }
            //using (var brush = new SolidBrush(Color.FromArgb(200, 255, 255, 255)))
            //{
            //    rects.ForEach(r => g.FillRectangle(brush, r));
            //}
        }
        #endregion

        #region 输入处理


        protected override void OnMouseDown(MouseEventArgs e)
        {
            LastMouseDown = DateTime.Now;

            if (e.Button == MouseButtons.Left)
            {
                _selection.StartPoint = e.Location;
                _selection.End = _selection.Start;
                //  var aa =  GetCharPosition(e.Location);
                IsMouseButtonsLeft = true;
            }
            else if (IsMouseButtonsLeft)
            {
                IsMouseButtonsLeft = false;

            }

            if (e.Button == MouseButtons.Left && _selection.IsValid)
            {
                _selection.IsValid = false;
                _selection.Start = GetCharPosition(e.Location);
                _selection.StartALT = GetCharPosition_ALT(e.Location);
                _selection.StartPoint = e.Location;
                _selection.End = _selection.Start;
                //  TriggerRefresh();
            }
            else if (e.Button != MouseButtons.Right)
            {
                _selection.Start = GetCharPosition(e.Location);
                _selection.StartALT = GetCharPosition_ALT(e.Location);
                // Console.WriteLine("OnMouseDown:  Count: "+Count+" vscrollBar.Value: " + vscrollBar.Value + " vscrollBar.max: " + vscrollBar.Maximum + " vscrollBar,LargeChange: " + vscrollBar.LargeChange + "  Row: " + _rows + " Cols: " + _cols + " _scrollOffset: " + (_scrollOffset / CharHeight).ToString() + " Count: " + _buffer.Count);
                _selection.End = _selection.Start;

            }
            else if (e.Button == MouseButtons.Right)
            {
                if (_selection.IsValid)
                {
                    this.toolStripMenuItem1.Enabled = true;
                    复制并粘贴ToolStripMenuItem.Enabled = true;
                }
                else
                {
                    this.toolStripMenuItem1.Enabled = false;
                    复制并粘贴ToolStripMenuItem.Enabled = false;

                }
            }
            TriggerRefresh();

            //Console.WriteLine("OnMouseDown");
            //Invalidate();
            //  TriggerRefresh();
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            if (e.Button == MouseButtons.Left && IsMouseButtonsLeft)
            {
                if ((DateTime.Now - LastMouseDown).TotalMilliseconds > 100)
                {
                    if (!_selection.IsValid)
                    {
                        _selection.IsValid = true;
                    }
                }

                if (IsAltDown && _selection.IsAltDown)
                {//都是列模式

                    //  Console.WriteLine("都在列默认是");
                    _selection.End = GetCharPosition(e.Location);
                    //   var End = GetCharPosition_ALT(e.Location);
                    _selection.EndALT = GetCharPosition_ALT(e.Location);
                    // _selection.End = GetMaxCharPosition(_selection.Start, End, e.Location);
                    _selection.EndPoint = e.Location;
                }
                else if (IsAltDown)
                {
                    //   Console.WriteLine("按下ALT键盘  ==》 更新选中区域为列模式");
                    _selection.IsAltDown = true;
                    _selection.End = GetCharPosition(e.Location);
                    //   var End = GetCharPosition_ALT(e.Location);
                    _selection.EndALT = GetCharPosition_ALT(e.Location);
                    //var End = GetCharPosition_ALT(e.Location);
                    //_selection.End = GetMaxCharPosition(_selection.Start, End, e.Location);
                }
                else if (_selection.IsAltDown)
                {
                    //   Console.WriteLine("取消 ALT 键盘按下状态  ==》 更新选中区域为普通模式");
                    _selection.IsAltDown = false;
                    _selection.End = GetCharPosition(e.Location);
                }
                else
                {
                    //   Console.WriteLine($" Start.Line: {_selection.Start.Line}  Start.Column: {_selection.Start.Column}  End.Line: { _selection.End.Line}  End.Column: {_selection.End.Column} ");
                    _selection.End = GetCharPosition(e.Location);
                }

                TriggerRefresh();

            }
        }

        private CharPosition GetMaxCharPosition(CharPosition Start, CharPosition End, Point Endpoint)
        {


            CharPosition start = Start;
            CharPosition end = End;
            // 确保起始列小于结束列
            if (start.Line > end.Line)
            {
                var temp = start;
                start = end;
                end = temp;
            }

            int MaxCol = 0;
            for (int line = start.Line; line <= end.Line; line++)
            {
                MaxCol = Math.Max(MaxCol, this.GetCharPosition(Endpoint, line).Column);

            }

            return new CharPosition(End.Line, MaxCol);



        }

        protected override void OnMouseWheel(MouseEventArgs e)
        {

            if (IsCtrlDown)
            {
                var lastzoom = zoom;
                if (zoom > 0.6 && zoom < 5)
                {
                    if (e.Delta > 0)
                    {
                        zoom += 0.1;
                        // Console.WriteLine("zoom += > ：  " + zoom);
                    }
                    else
                    {
                        zoom -= 0.1;
                        // Console.WriteLine("zoom -= > ：  " + zoom);
                    }

                    if (zoom <= 0.6 || zoom >= 5)
                    {
                        zoom = lastzoom;
                        //    Console.WriteLine("zoom -= > ：超过最大值 or 小于最小值  ==》无变化，  "+ lastzoom);
                    }
                    else
                    {
                        //  Console.WriteLine("OnMouseWheel 更新值");
                        InitializeMetrics(zoom);


                        if (_HistroylineInfo.Count + _CulineInfo.Count > _rows)
                        {
                            _scrollOffset = (_HistroylineInfo.Count + _CulineInfo.Count - _rows) * (int)CharHeight;
                            UpdateScrollBars(_scrollOffset);
                            //_scrollOffset += (int)CharHeight;
                            // _scrollOffset = (int)Math.Max(0, this.vscrollBar.Maximum - _rows + 1) * (int)CharHeight;
                        }
                        TriggerRefresh();
                    }


                }

            }
            else
            {
                if (e.Delta > 0)
                {
                    OnScroll(new ScrollEventArgs(ScrollEventType.SmallDecrement, -3));
                }
                else
                {
                    ///下滑
                    OnScroll(new ScrollEventArgs(ScrollEventType.SmallIncrement, 3));
                }
            }


        }

        protected override void OnMouseUp(MouseEventArgs e)
        {
            LastMouseDown = DateTime.Now;
            IsMouseButtonsLeft = false;
            base.OnMouseUp(e);
        }

        protected override void OnMouseLeave(EventArgs e)
        {
            LastMouseDown = DateTime.Now;
            IsMouseButtonsLeft = false;
            //  _selection.IsValid = false;
            base.OnMouseLeave(e);
        }

        protected override void OnMouseClick(MouseEventArgs e)
        {
            //Console.WriteLine("OnMouseClick单击");
            base.OnMouseClick(e);
        }

        protected override void OnMouseDoubleClick(MouseEventArgs e)
        {
            // Console.WriteLine("双击");

            // 获取双击位置对应的行号
          //  int line = (e.Y + _scrollOffset) / (int)_charSize.Height;
            int line = (e.Y + _scrollOffset) / (int)CharHeight;
            
            line = Clamp(line, 0, _buffer.Count - 1);
            // 计算该行的起始和结束列索引
            int startColumn = 0;
            int endColumn = _buffer[line].Length - 1;
            // 设置选择区域
            _selection.Start = new CharPosition(line, startColumn);
            _selection.End = new CharPosition(line, endColumn);
            IsAltDown = false;
            _selection.IsValid = true;
            _selection.IsAltDown = false;
            this.Invalidate();
            // base.OnMouseDoubleClick(e);
        }

        protected override void OnScroll(ScrollEventArgs se)
        {

            if (_buffer.Count < _rows)
            {
                return;
            }
            if (!VScroll)
            {

                switch (se.Type)
                {


                    case ScrollEventType.Last: //滚动框被移动到 Maximum 位置。
                        Console.WriteLine("ScrollEventType.Last");
                        break;
                    case ScrollEventType.SmallIncrement: //下移动
                        //下
                   //     _scrollOffset += se.NewValue * (int)_charSize.Height; //8426 +22+22
                        _scrollOffset += se.NewValue * (int)CharHeight; //8426 +22+22

                   //     var aa = _charSize.Height * (_buffer.Count - _rows + 3); //8360
                 //       _scrollOffset = (int)Math.Min(_scrollOffset, _charSize.Height * (_HistroylineInfo.Count + _CulineInfo.Count - _rows));
                        _scrollOffset = (int)Math.Min(_scrollOffset, CharHeight * (_HistroylineInfo.Count + _CulineInfo.Count - _rows));
                        UpdateScrollBars(_scrollOffset);
                        //if (_scrollOffset > _charSize.Height * (_buffer.Count - _rows))
                        //{
                        //    _scrollOffset = (int)_charSize.Height * (_buffer.Count - _rows);
                        //}
                        //  Invalidate();
                        TriggerRefresh();
                        break;
                    case ScrollEventType.SmallDecrement:

                        //上
                     //   _scrollOffset += se.NewValue * (int)_charSize.Height;
                        _scrollOffset += se.NewValue * (int)CharHeight;
                        _scrollOffset = Math.Max(0, _scrollOffset);
                        UpdateScrollBars(_scrollOffset);
                        //if (_scrollOffset < 0)
                        //{
                        //    _scrollOffset = 0;
                        //}
                        //   Invalidate();
                        TriggerRefresh();
                        break;
                    case ScrollEventType.LargeDecrement: //滚动框移动了较长的距离 上

                        //上
                        break;
                    case ScrollEventType.LargeIncrement:  //滚动框移动了较长的距离  下
                        //下
                        break;
                    case ScrollEventType.First: // 滚动框被移动到 Minimum 位置。
                                                // Console.WriteLine("ScrollEventType.First");
                        break;
                    case ScrollEventType.ThumbPosition: //滚动框被移动。
                        break;
                    case ScrollEventType.ThumbTrack: //滚动框当前正在移动。
                                                     //  Invalidate();
                        TriggerRefresh();
                        break;
                    case ScrollEventType.EndScroll://滚动框已停止移动。
                        break;
                    default:
                        break;
                }



            }




        }



        protected override void OnKeyUp(KeyEventArgs e)
        {
            if (e.KeyData == Keys.Menu && IsAltDown)
            {

                IsAltDown = false;
                ///  MessageBox.Show("alt");
            }
            else if (e.Alt)
            {
                IsAltDown = false;
                //   MessageBox.Show("alt");
            }
            else if (e.KeyData == Keys.Alt)
            {
                IsAltDown = false;
                // MessageBox.Show("alt");
            }
            else if (e.KeyCode == Keys.ControlKey)
            {
                IsCtrlDown = false;
                //   MessageBox.Show("alt");
            }
            else if (e.KeyData == Keys.Menu)
            {
                IsAltDown = false;
                //   MessageBox.Show("alt");
            }
            //  Console.WriteLine(e.KeyData);
            base.OnKeyUp(e);




        }
        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.C)
            {
                // CopySelection();
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Alt)
            {
                IsAltDown = true;
                base.OnKeyDown(e);
            }
            else if (e.Alt)
            {
                IsAltDown = true;

                e.Handled = false;
            }
            else if (e.KeyCode == Keys.ControlKey)
            {
                IsCtrlDown = true;
                // e.Handled = false;
            }
            base.OnKeyDown(e);



            // e.Handled = true;
            // 其他键盘处理...
        }
        protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e)
        {
            base.OnPreviewKeyDown(e);
        }

        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r') // Enter键
            {
                OnInPutData('\r');
            }
            else if (e.KeyChar == '\b') // 退格键
            {
                OnInPutData('\b');
            }
            else if (e.KeyChar == 0x03)
            {
                OnInPutData(e.KeyChar);
            }

            else
            {
                OnInPutData(e.KeyChar);
                base.OnKeyPress(e);
                //_currentInput.Append(e.KeyChar);
                //Write(e.KeyChar, _currentColor);

            }

        }
        protected override bool ProcessDialogKey(Keys keyCode)
        {
            if (keyCode == Keys.Tab)
            {
                OnInPutData('\t');
                return true;
            }
            //else if(keyCode == Keys.ControlKey)
            //{
            //    IsCtrlDown = true;
            //    return false;
            //}
            else if (keyCode == Keys.PageUp)
            {
                _scrollOffset = Math.Min((int)((_scrollOffset - _rows) * CharHeight), 0);
                this.vscrollBar.Value = (_scrollOffset / (int)CharHeight) + 1;
                return true;
            }
            else if (keyCode == Keys.PageDown)
            {
                return true;
            }
            else if (keyCode == Keys.Up || keyCode == Keys.Down || keyCode == Keys.Left || keyCode == Keys.Right)
            {

                switch (keyCode)
                {
                    case Keys.Up:
                        //  char d = (char)16;
                        OnInPutData((char)16);

                        break;
                    case Keys.Down:
                        OnInPutData((char)14);
                        break;
                    case Keys.Left:
                        // byte[] temp = new byte[] { 0x1b, 0x5b, 0x44 };
                        OnInPutData(new byte[] { 0x1b, 0x5b, 0x44 });
                        break;
                    case Keys.Right:
                        OnInPutData(new byte[] { 0x1b, 0x5b, 0x43 });
                        break;

                    default:
                        break;

                }
                return true;
            }
            else
                return base.ProcessDialogKey(keyCode);
        }

        protected override void OnLostFocus(EventArgs e)
        {
            if (IsAltDown)
            {
                IsAltDown = false;
            }
            base.OnLostFocus(e);
        }



        /// <summary>
        /// 键盘输入 触发事件 便于回调
        /// </summary>
        /// <param name="bytes"></param>
        protected void OnInPutData(byte[] bytes)
        {
            OnDataRequested?.Invoke(bytes);
            //OnDataRequested(bytes);
            // KeyInputData?.Invoke(null, bytes);
        }

        /// <summary>
        /// 键盘输入 触发事件 便于回调
        /// </summary>
        /// <param name="cha"></param>
        protected void OnInPutData(char cha)
        {
            // Console.Write(cha);
            // OnInPutData(BitConverter.GetBytes(cha));

            OnInPutData(new byte[] { (byte)cha });

        }

        /// <summary>
        /// 删除字符串
        /// </summary>
        //private void RemoveLastCharacter()
        //{
        //    if (_buffer.Count > 0)
        //    {
        //        var lastLine = _buffer.Last();
        //        if (lastLine.Length > 0)
        //        {
        //            lastLine.Remote();
        //            //var lastSegment = lastLine.Segments.Last();
        //            //lastLine.Segments.Remove(lastSegment);
        //            //重置文字颜色
        //            lastLine.RestColor();
        //            if (keywordColors.Count > 0)
        //            {
        //                if (!KeyWordColorMatch(lastLine))
        //                {
        //                    TriggerRefresh();
        //                }
        //            }
        //            else
        //            {
        //                TriggerRefresh();
        //            }


        //            //  Invalidate();

        //        }
        //    }
        //}



        protected override void OnResize(EventArgs e)
        {
            if (delayTimer == null)
            {
                return;
            }
            // Console.WriteLine(this.Width + " " + this.Height);
            if (this.Width == 0 || this.Height == 0)
            {
                IsResize = false;
                base.OnResize(e);
                return;
                // Console.WriteLine("OnResize" + " = 0");
            }
            base.OnResize(e);
            if (!IsResize)
            {

                IsResize = true;
                //  每次窗口大小变化时先停止定时器（如果正在运行），然后重新启动定时器
                if (delayTimer.Enabled)
                {
                    delayTimer.Stop();
                }
                delayTimer.Start();
            }


            //  base.OnResize(e);
            //InitializeMetrics();
            //Invalidate();
        }
        #endregion

        #region 核心功能

        /// <summary>
        /// 回显 远端接受到的输入
        /// </summary>
        /// <param name="text"></param>
        public void WriteByte(string text)
        {
            if (text == null)
            {
                return;
            }

            //   byte[] bytes = Encoding.UTF8.GetBytes(text);
            foreach (VT100Command command in this.VT100Parser(text.ToArray()))
            {
                switch (command.Action)
                {
                    case VT100Action.NormalChar:
                        TerminalLine line = _buffer.Last();
                        line.AddRange(command.colorChars);
                        _CulineInfo = line.GetCuLineInfo(_buffer.Count - 1, this._cols);
                        // Console.WriteLine($" Cout: {Count} _histroy.count {_HistroylineInfo.Count}  _CulineInfo.Count: {_CulineInfo.Count} _buffer.Count: {_buffer.Count} vscrollBar.Value: {vscrollBar.Value} vscrollBar.max: {vscrollBar.Maximum} VerticalScroll,LargeChange: {vscrollBar.LargeChange} rows: {_rows}");
                        InCharOrMoveUpdata_scrollOffset();
                        if (this.colorMatcher.Count > 0)
                        {
                            KeyWordColorMatch(line);
                            //if (!KeyWordColorMatch(line))
                            //{
                            //    TriggerRefresh();
                            //}
                        }
                        TriggerRefresh();
                        //else
                        //{
                        //    TriggerRefresh();
                        //}

                        break;
                    case VT100Action.NormanlNewLine:
                        NewLine();
                        TriggerRefresh();
                        break;
                    case VT100Action.Bell:
                        break;
                    case VT100Action.CursorUp:
                        break;
                    case VT100Action.CursorDown:
                        break;
                    case VT100Action.CursorLeft:

                        _buffer.Last()?.CursorLeft(command.Parameters[0]);
                        TriggerRefresh();

                        break;
                    case VT100Action.Black:
                        //退格键盘不是删除，= 等于左移动为1
                        // RemoveLastCharacter();
                        _buffer.Last()?.CursorLeft(1);
                        TriggerRefresh();
                        break;

                    case VT100Action.CursorRight:
                        _buffer.Last()?.CursorRight(command.Parameters[0]);
                        TriggerRefresh();
                        break;
                    case VT100Action.ClearLine:
                        _buffer.Last()?.ClearLine();
                        TriggerRefresh();
                        break;
                    case VT100Action.CarriageReturn:
                        _buffer.Last()?.CarriageReturn();
                        break;

                    default:
                        break;

                }
            }
            // this.Invalidate();



        }


        ///// <summary>
        ///// 关键字功能 颜色字典
        ///// </summary>
        //public Dictionary<string, Color> keywordColors = new Dictionary<string, Color>()
        //{
        //    {"show ", Color.Red },
        //     {"down ", Color.Red },
        //    {"shutdown ", Color.Yellow },
        //      //{"interface ", Color.Blue },
        //      //  {"gei", Color.Yellow },
        //      //  {"xgei", Color.Yellow },
        //      //  {"cgei", Color.Yellow },
        //      //  {"smartgroup", Color.Yellow },
        //          {"eth", Color.Yellow },

        //   // {"(no(t)?(connect)?)|((shut)?(down)?)",Color.Red }
        //};


        /// <summary>
        /// 匹配正则表达式，更新颜色  返回 有更新或无更新
        /// </summary>
        /// <param name="line"></param>
        /// <returns></returns>
        private bool KeyWordColorMatch(TerminalLine line)
        {
            //// 构建正则表达式模式
            //string pattern = string.Join("|", keywordColors.Keys.Select(k => Regex.Escape(k)));
            //Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);

            //// 查找所有匹配项
            //MatchCollection matchCollection = regex.Matches(line.ToString());
            //foreach (Match match in matchCollection)
            //{
            //    string keyword = match.Value;
            //    Color color = keywordColors[keyword.ToLower()];
            //    UpdataColorTerminalLine(line, match.Index, match.Length, color);
            //    // matches.Add((match.Index, match.Index + match.Length, color));
            //}

            //  colorMatcher.UpdataColorChar(line);
            ///最好只重绘这一行，后期优化
            if (colorMatcher.UpdataColorChar(line))
            {
                ///匹配到了，更新一下显示效果
              //  Invalidate();
                TriggerRefresh();
                return true;
            }
            else
            {
                return false;
            }

        }

        /// <summary>
        /// 正则表达式匹配更新关键字
        /// </summary>
        /// <param name="line"></param>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <param name="color"></param>
        private void UpdataColorTerminalLine(TerminalLine line, int start, int length, Color color)
        {
            for (int i = 0; i < length; i++)
            {
                line.UpdataColor(i + start, color);
                //  line.Segments[i+start].CharColor = color;
            }

        }



        /// <summary>
        /// 在指定区域写入  测试用
        /// </summary>
        /// <param name="rectangleF"></param>
        /// <param name="colorChar"></param>
        private void Invalidate(PointF rectangleF, char colorChar)
        {
            graphics.DrawString(colorChar.ToString(), this.Font, white, rectangleF.X, rectangleF.Y, stringFormat);
            //Console.WriteLine("Invalidate：  总行数：" + rectangleF.ToString());
            //using (var g = this.CreateGraphics())
            //{
            //    graphics.DrawString(colorChar.ToString(), this.Font, white, rectangleF.X, rectangleF.Y, stringFormat);
            //}
        }


        /// <summary>
        /// 上一次的总数
        /// </summary>
        private int LastSum = 0;

        /// <summary>
        /// 当前的数量
        /// </summary>
        private int Count
        {
            get
            {
                LastSum = _HistroylineInfo.Count + Math.Max(1, _CulineInfo.Count);
                return LastSum;
            }
        }



        /// <summary>
        /// 添加新的行数
        /// </summary>
        /// <returns></returns>
        private TerminalLine NewLine()
        {
            var line = new TerminalLine();
            //lock (locket)
            //{
            if (_buffer.Count > 0)
            {
                _buffer.Last().IsCursor = false;
            }

            lock (LocketUpdata)
            {
                _buffer.Add(line);
                _HistroylineInfo.AddRange(_CulineInfo);
                _CulineInfo.Clear();
                _CulineInfo.AddRange(line.GetCuLineInfo(_buffer.Count - 1, _cols));

            }

            //_CulineInfo.Add(new LineInfo(_buffer.Count-1));



            TriggerVscroPerformRefresh();
            //   this.vscrollBar.ResumeLayout(); // 恢复布局更新并强制立即更新

            TriggerRefresh();
            return line;
        }

        /// <summary>
        /// 插入字符时，更新光标的位置到最新
        /// </summary>
        private void InCharOrMoveUpdata_scrollOffset()
        {
            if ((_HistroylineInfo.Count + _CulineInfo.Count) > _rows)
            {

                if (_scrollOffset != (_HistroylineInfo.Count + _CulineInfo.Count - _rows) * (int)CharHeight)
                {
                    _scrollOffset = (_HistroylineInfo.Count + _CulineInfo.Count - _rows) * (int)CharHeight;
                    //  UpdateScrollBars(_scrollOffset);
                    this.TriggerVscroPerformRefresh();
                }


                //_scrollOffset += (int)CharHeight;
                // _scrollOffset = (int)Math.Max(0, this.vscrollBar.Maximum - _rows + 1) * (int)CharHeight;
            }
        }


        /// <summary>
        /// 复制功能
        /// </summary>
        public void CopySelection()
        {
            if (!_selection.IsValid) return;

            var text = GetSelectedText();
            if (text != null)
            {
                try
                {
                    Clipboard.SetText(text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

        }
        #endregion

        #region 辅助方法

        ///// <summary>
        ///// 根据鼠标点击位置  行数与列数的位置
        ///// </summary>
        ///// <param name="pt"></param>
        ///// <returns></returns>
        //private CharPosition GetCharPosition(Point pt)
        //{
        //    int line = (pt.Y + _scrollOffset) / (int)_charSize.Height;
        //    int col = pt.X / (int)_charSize.Width;

        //    line = Clamp(line, 0, _buffer.Count - 1);
        //    col = Clamp(col, 0, _buffer[line].Length - 1);

        //    return new CharPosition(line, col);
        //}

        /// <summary>
        /// /根据鼠标点击位置  行数与列数的位置 ，支持中文
        /// </summary>
        /// <param name="pt"></param>
        /// <returns></returns>
        private CharPosition GetCharPosition1(Point pt)
        {
        //    int line = (pt.Y + _scrollOffset) / (int)_charSize.Height;
            int line = (pt.Y + _scrollOffset) / (int)CharHeight;
            line = Clamp(line, 0, _buffer.Count - 1);
            int col = 0;
            float currentX = 0;
            TerminalLine currentLine = _buffer[line];
            for (int i = 0; i < currentLine.Length; i++)
            {
                char c = currentLine.GetColorChar(i).Char;
                int charWidth = IsChinese(c) ? 2 : 1;
                float charWidthInPixels = charWidth * _charSize.Width;
                if (currentX + charWidthInPixels > pt.X)
                {
                    break;
                }
                col++;
                currentX += charWidthInPixels;
            }
            col = Clamp(col, 0, currentLine.Length - 1);
            return new CharPosition(line, col);
        }


        /// <summary>
        /// /根据鼠标点击位置  行数与列数的位置 ，支持中文
        /// </summary>
        /// <param name="pt"></param>
        /// <returns></returns>
        private CharPosition GetCharPosition(Point pt)
        {
            //   int line = (pt.Y + _scrollOffset) / (int)_charSize.Height;
            int line = (pt.Y + _scrollOffset) / (int)CharHeight;
            line = Clamp(line, 0, Count - 1);
            int col = 0;
            float currentX = 0;


            LineInfo currentLine = null;
            //     TerminalLine currentLine = null;
            if (line < _HistroylineInfo.Count)
            {
                currentLine = _HistroylineInfo[line];
                //  currentLine =  _buffer[ _HistroylineInfo[line].LineIndex];
            }
            else
            {
                currentLine = _CulineInfo[(line - _HistroylineInfo.Count)];
            }

            //  TerminalLine currentLine = _buffer[line];


            for (int i = currentLine.Start; i < currentLine.End; i++)
            {
                char c = _buffer[currentLine.LineIndex].GetColorChar(i).Char;
                int charWidth = IsChinese(c) ? 2 : 1;
                float charWidthInPixels = charWidth * _charSize.Width;
                if (currentX + charWidthInPixels > pt.X)
                {
                    break;
                }
                col++;
                currentX += charWidthInPixels;
            }


            col = Clamp(col, 0, currentLine.End - currentLine.Start - 1);
            return new CharPosition(line, col);
        }
        /// <summary>
        /// /根据鼠标点击位置  行数与列数的位置 ，支持中文
        /// </summary>
        /// <param name="pt"></param>
        /// <returns></returns>
        private CharPosition GetCharPosition_ALT(Point pt)
        {
         //   int line = (pt.Y + _scrollOffset) / (int)_charSize.Height;
            int line = (pt.Y + _scrollOffset) / (int)CharHeight;
            line = Clamp(line, 0, Count - 1);
            //  int col = 0;
            float currentX = 0;
            int col = (int)pt.X / (int)_charSize.Width;
            return new CharPosition(line, col);
            LineInfo currentLine = null;
            //     TerminalLine currentLine = null;
            if (line < _HistroylineInfo.Count)
            {
                currentLine = _HistroylineInfo[line];
                //  currentLine =  _buffer[ _HistroylineInfo[line].LineIndex];
            }
            else
            {
                currentLine = _CulineInfo[(line - _HistroylineInfo.Count)];
            }

            //  TerminalLine currentLine = _buffer[line];


            for (int i = currentLine.Start; i < currentLine.End; i++)
            {
                char c = _buffer[currentLine.LineIndex].GetColorChar(i).Char;
                int charWidth = IsChinese(c) ? 2 : 1;
                float charWidthInPixels = charWidth * _charSize.Width;
                if (currentX + charWidthInPixels > pt.X)
                {
                    break;
                }
                col++;
                currentX += charWidthInPixels;
            }


            col = Clamp(col, 0, currentLine.End - currentLine.Start - 1);
            return new CharPosition(line, col);
        }



        /// <summary>
        /// 取得指定行的 位置
        /// </summary>
        /// <param name="pt"></param>
        /// <param name="line"></param>
        /// <returns></returns>
        private CharPosition GetCharPosition(Point pt, int line)
        {
            //    int line = (pt.Y + _scrollOffset) / (int)_charSize.Height;
            line = Clamp(line, 0, Count - 1);
            int col = 0;
            float currentX = 0;

            LineInfo currentLine = null;
            //     TerminalLine currentLine = null;
            if (line < _HistroylineInfo.Count)
            {
                currentLine = _HistroylineInfo[line];
                //  currentLine =  _buffer[ _HistroylineInfo[line].LineIndex];
            }
            else
            {
                currentLine = _CulineInfo[(line - _HistroylineInfo.Count)];
            }

            //  TerminalLine currentLine = _buffer[line];

            for (int i = currentLine.Start; i < currentLine.End; i++)
            {
                char c = _buffer[currentLine.LineIndex].GetColorChar(i).Char;
                int charWidth = IsChinese(c) ? 2 : 1;
                float charWidthInPixels = charWidth * _charSize.Width;
                if (currentX + charWidthInPixels > pt.X)
                {
                    break;
                }
                col++;
                currentX += charWidthInPixels;
            }
            //for (int i = 0; i < currentLine.Length; i++)
            //{
            //    char c = currentLine.GetColorChar(i).Char;
            //    int charWidth = IsChinese(c) ? 2 : 1;
            //    float charWidthInPixels = charWidth * _charSize.Width;
            //    if (currentX + charWidthInPixels > pt.X)
            //    {
            //        break;
            //    }
            //    col++;
            //    currentX += charWidthInPixels;
            //}
            col = Clamp(col, 0, currentLine.End - currentLine.Start - 1);
            return new CharPosition(line, col);
        }





        // 手动实现的 Clamp 方法
        private int Clamp(int value, int min, int max)
        {
            return Math.Max(min, Math.Min(value, max));
        }


        /// <summary>
        /// 选择辅助，取得RectangleF 列表 支持列模式/按 Alt键盘
        /// </summary>
        /// <returns></returns>
        private List<RectangleF> CalculateSelectionRects()
        {
            if (IsAltDown || _selection.IsAltDown)
            {
                ///列模式
                return CalculateSelectionRectsAlt();
            }
            var rects = new List<RectangleF>();
            if (!_selection.IsValid) return rects;

            CharPosition start = _selection.Start;
            CharPosition end = _selection.End; ;
            if (_selection.Start.Line == _selection.End.Line)
            {
                if (_selection.Start.Column > _selection.End.Column)
                {
                    start = _selection.End;
                    end = _selection.Start;
                }
            }
            else if (_selection.Start.Line > _selection.End.Line)
            {
                start = _selection.End;
                end = _selection.Start;
            }
            ///单行选中
            if (start.Line == end.Line)
            {
                //float IsLastChinese = 0;
                for (int index = start.Column; index <= end.Column; index++)
                {
                    ///计算中文字符的便宜量
                    ///
                    LineInfo terminalLine = null;
                    //  TerminalLine terminalLine = _buffer[start.Line];
                    if (start.Line < _HistroylineInfo.Count)
                    {
                        terminalLine = _HistroylineInfo[start.Line];
                    }
                    else
                    {
                        terminalLine = _CulineInfo[start.Line - _HistroylineInfo.Count];
                    }

                    int OffSet = _buffer[terminalLine.LineIndex].GetStartOffsetIndex(terminalLine.Start, terminalLine.Start + index);


                    // int OffSet= _buffer[terminalLine.Index].GetStartOffsetIndex(index);
              //      float yPos = start.Line * _charSize.Height - _scrollOffset;
               
                    float yPos = start.Line * CharHeight - _scrollOffset;
                    //  float xStart = index * _charSize.Width + 3 + IsLastChinese;
                    float xStart = OffSet * _charSize.Width + 3;

                    if (terminalLine.Count > index)
                    {
                        char? character = _buffer[terminalLine.LineIndex].GetColorChar(index + terminalLine.Start)?.Char;
                        if (character.HasValue)
                        {
                            if (IsChinese(character))
                            {
                           //     rects.Add(new RectangleF(xStart, yPos, _charSize.Width * 2, _charSize.Height));
                                rects.Add(new RectangleF(xStart, yPos, _charSize.Width * 2,CharHeight));
                                // IsLastChinese += _charSize.Width;
                            }
                            else
                            {
                        //        rects.Add(new RectangleF(xStart, yPos, _charSize.Width, _charSize.Height));
                                rects.Add(new RectangleF(xStart, yPos, _charSize.Width, CharHeight));
                            }
                        }
                    }
                }
            }
            else
            {
                ///多行选中
                for (int line = start.Line; line <= end.Line; line++)
                {
                    if (line < 0 || line >= this.Count)
                    {
                        continue;
                    }


                    if (line == start.Line)
                    {
                        ///首行
                        LineInfo terminalLine = null;
                        //  TerminalLine terminalLine = _buffer[start.Line];
                        if (start.Line < _HistroylineInfo.Count)
                        {
                            terminalLine = _HistroylineInfo[start.Line];
                        }
                        else
                        {
                            terminalLine = _CulineInfo[start.Line - _HistroylineInfo.Count];
                        }
                        for (int index = start.Column; index <= terminalLine.End; index++)
                        {
                            ///计算中文字符的便宜量
                            ///


                            int OffSet = _buffer[terminalLine.LineIndex].GetStartOffsetIndex(terminalLine.Start, terminalLine.Start + index);


                            // int OffSet= _buffer[terminalLine.Index].GetStartOffsetIndex(index);
                       //     float yPos = start.Line * _charSize.Height - _scrollOffset;
                            float yPos = start.Line * CharHeight - _scrollOffset;


                            //  float xStart = index * _charSize.Width + 3 + IsLastChinese;
                            float xStart = OffSet * _charSize.Width + 3;

                            if (terminalLine.Count > index)
                            {
                                char? character = _buffer[terminalLine.LineIndex].GetColorChar(index + terminalLine.Start)?.Char;
                                if (character.HasValue)
                                {
                                    if (IsChinese(character))
                                    {
                                     //   rects.Add(new RectangleF(xStart, yPos, _charSize.Width * 2, _charSize.Height));
                                        rects.Add(new RectangleF(xStart, yPos, _charSize.Width * 2, CharHeight));
                                        // IsLastChinese += _charSize.Width;
                                    }
                                    else
                                    {
                                     //   rects.Add(new RectangleF(xStart, yPos, _charSize.Width, _charSize.Height));
                                        rects.Add(new RectangleF(xStart, yPos, _charSize.Width, CharHeight));
                                    }
                                }
                            }
                        }
                        //LineInfo terminalLine = null;
                        ////  TerminalLine terminalLine = _buffer[start.Line];
                        //if (line <= _HistroylineInfo.Count)
                        //{
                        //    terminalLine = _HistroylineInfo[line];
                        //}
                        //else
                        //{
                        //    terminalLine = _CulineInfo[line - _HistroylineInfo.Count];
                        //}

                        /////计算中文字符的便宜量
                        ////   int OffSet = _buffer[start.Line].GetStartOffsetIndex(start.Column);
                        //int startCol;
                        //try
                        //{
                        //    startCol = _buffer[terminalLine.LineIndex].GetStartOffsetIndex(terminalLine.Start, start.Column);

                        //}
                        //catch(Exception ex)
                        //{
                        //    startCol = start.Column;
                        //}

                        //                            // int startCol = start.Column;
                        //int endCol = terminalLine.Count;
                        //float yPos = line * _charSize.Height - _scrollOffset;
                        //float xStart = startCol * _charSize.Width + 3;
                        //float xEnd = (endCol) * _charSize.Width + 3;
                        //rects.Add(new RectangleF(xStart, yPos, xEnd - xStart, _charSize.Height));
                    }
                    else if (line == end.Line)
                    {
                        LineInfo terminalLine = null;
                        //  TerminalLine terminalLine = _buffer[start.Line];
                        if (line < _HistroylineInfo.Count)
                        {
                            terminalLine = _HistroylineInfo[line];
                        }
                        else
                        {
                            terminalLine = _CulineInfo[line - _HistroylineInfo.Count];
                        }
                        int startCol = 0;
                        //  int endCol = end.Column;
                        int endCol = _buffer[terminalLine.LineIndex].GetStartOffsetIndex(terminalLine.Start, terminalLine.Start + end.Column);
                     //   float yPos = line * _charSize.Height - _scrollOffset;
                        float yPos = line * CharHeight - _scrollOffset;
                        float xStart = startCol * _charSize.Width + 3;
                        float xEnd = (endCol + 1) * _charSize.Width + 3;
                        //    Console.WriteLine($"{line} startCol: {startCol} {line}endCol：{endCol}");
                      //  rects.Add(new RectangleF(xStart, yPos, xEnd - xStart, _charSize.Height));
                        rects.Add(new RectangleF(xStart, yPos, xEnd - xStart, CharHeight));
                    }
                    else
                    {
                        LineInfo terminalLine = null;
                        //  TerminalLine terminalLine = _buffer[start.Line];
                        if (line <= _HistroylineInfo.Count)
                        {
                            terminalLine = _HistroylineInfo[line];
                        }
                        else
                        {
                            terminalLine = _CulineInfo[line - _HistroylineInfo.Count];
                        }
                        int startCol = 0;
                        // int endCol = _buffer[line].Length;
                        int endCol = _buffer[terminalLine.LineIndex].GetStartOffsetIndex(terminalLine.Start, terminalLine.End);
                      //  float yPos = line * _charSize.Height - _scrollOffset;
                        float yPos = line * CharHeight - _scrollOffset;
                        float xStart = startCol * _charSize.Width + 3;
                        float xEnd = (endCol) * _charSize.Width + 3;
                      //  rects.Add(new RectangleF(xStart, yPos, xEnd - xStart, _charSize.Height));
                        rects.Add(new RectangleF(xStart, yPos, xEnd - xStart, CharHeight));
                    }

                }

            }

            return rects;
        }

        //private bool IsAltDown { get; set; } // 假设这个属性用于判断 Alt 键是否按下

        /// <summary>
        /// 取得列默认选中区域
        /// </summary>
        /// <returns></returns>
        private List<RectangleF> CalculateSelectionRectsAlt()
        {
            var rects = new List<RectangleF>();
            if (!_selection.IsValid) return rects;
            // 找出最小的 X 和 Y 坐标作为左上角坐标
            //float x = Math.Min(_selection.StartPoint.X, _selection.EndPoint.X);
            //float y = Math.Min(_selection.StartPoint.Y, _selection.EndPoint.Y);

            //// 计算宽度和高度
            //float width = Math.Abs(_selection.StartPoint.X - _selection.EndPoint.X);
            //float height = Math.Abs(_selection.StartPoint.Y - _selection.EndPoint.Y);

            //rects.Add( new RectangleF(x, y, width, height));


            //rects.Add(new RectangleF(_selection.StartPoint.X, _selection.StartPoint.Y));
            //  if (_selection.StartPoint > _selection.EndPoint)


            CharPosition start = _selection.StartALT;
            CharPosition end = _selection.EndALT;
            if (start.Line > end.Line)
            {
                var temp = start;
                start = end;
                end = temp;
            }

            int StartCol = Math.Min(start.Column, end.Column);
            int EndCol = Math.Max(start.Column, end.Column);
            //  LineInfo terminalLine = null;
            //  Console.WriteLine($"StartCol: {StartCol}  EndCol: {EndCol} ");
            //for (int line = start.Line; line <= end.Line; line++)
            //{

            //    //  TerminalLine terminalLine = _buffer[start.Line];
            //    if (line < _HistroylineInfo.Count)
            //    {
            //        terminalLine = _HistroylineInfo[line];
            //    }
            //    else
            //    {
            //        terminalLine = _CulineInfo[line - _HistroylineInfo.Count];
            //    }
            //    if (line < 0 || line >= this.Count)
            //    {
            //        continue;
            //    }
            //    EndCol = Math.Max(_buffer[terminalLine.LineIndex].GetStartOffsetIndex(terminalLine.Start, terminalLine.End), EndCol);
            //}




            for (int line = start.Line; line <= end.Line; line++)
            {
                //if (line < 0 || line >= _buffer.Count)
                //{
                //    continue;
                //}
                //  EndCol = Math.Max(_buffer[line].GetStartOffsetIndex(EndCol), EndCol);
             //   float yPos = line * _charSize.Height - _scrollOffset;
                float yPos = line * CharHeight - _scrollOffset;
                float xStart = StartCol * _charSize.Width + 3;
                float xEnd = (EndCol + 1) * _charSize.Width + 3;
                // Console.WriteLine($"AAAAAAAAA ====> xStart: {xStart}  xEnd: {xEnd} ");
            //    rects.Add(new RectangleF(xStart, yPos, xEnd - xStart, _charSize.Height));
                rects.Add(new RectangleF(xStart, yPos, xEnd - xStart, CharHeight));
            }

            return rects;
        }


        /// <summary>
        /// 取得复制的文本
        /// </summary>
        /// <returns></returns>
        private string GetSelectedText()
        {
            if (!_selection.IsValid) return "";

            if (_selection.IsAltDown)
            {
                return GetSelectedTextALt();
            }


            CharPosition start = _selection.Start;
            CharPosition end = _selection.End; ;
            if (_selection.Start.Line == _selection.End.Line)
            {
                if (_selection.Start.Column > _selection.End.Column)
                {
                    start = _selection.End;
                    end = _selection.Start;
                }
            }
            else if (_selection.Start.Line > _selection.End.Line)
            {
                start = _selection.End;
                end = _selection.Start;
            }

            var sb = new StringBuilder();
            LineInfo terminalLine = null;
            if (start.Line == end.Line)
            {

                //  TerminalLine terminalLine = _buffer[start.Line];
                if (start.Line < _HistroylineInfo.Count)
                {
                    terminalLine = _HistroylineInfo[start.Line];
                }
                else
                {
                    terminalLine = _CulineInfo[start.Line - _HistroylineInfo.Count];
                }

                var line = _buffer[terminalLine.LineIndex];
                int startIndex = GetSegmentIndexAtColumn(line, terminalLine.Start + start.Column);
                int endIndex = GetSegmentIndexAtColumn(line, terminalLine.Start + end.Column);

                for (int i = startIndex; i <= endIndex; i++)
                {
                    var segment = line.GetColorChar(i);
                    sb.Append(segment.Char);

                }
            }
            else
            {


                for (int linenum = start.Line; linenum <= end.Line; linenum++)
                {


                    if (linenum < _HistroylineInfo.Count)
                    {
                        terminalLine = _HistroylineInfo[linenum];
                    }
                    else
                    {
                        terminalLine = _CulineInfo[linenum - _HistroylineInfo.Count];
                    }

                    var startLine = _buffer[terminalLine.LineIndex];

                    int startIndex = Math.Max(0, GetSegmentIndexAtColumn(startLine, terminalLine.Start + start.Column));


                    //搜行
                    if (linenum == start.Line)
                    {
                        //   int endIndex = GetSegmentIndexAtColumn(startLine, terminalLine.Start + end.Column);
                        for (int i = startIndex; i < terminalLine.End; i++)
                        {
                            var segment = startLine.GetColorChar(terminalLine.Start + i);
                            sb.Append(segment.Char);

                        }
                        sb.AppendLine();
                    }

                    else if (linenum != end.Line)
                    {
                        for (int i = startIndex; i < terminalLine.End; i++)
                        {
                            var segment = startLine.GetColorChar(i);
                            sb.Append(segment.Char);
                            //if (i == startIndex)
                            //{
                            //    sb.Append(segment.Text.Substring(start.Column - GetColumnOfSegment(startLine, i)));
                            //}
                            //else
                            //{
                            //    sb.Append(segment.Text);
                            //}

                        }
                        sb.AppendLine();
                    }
                    else
                    {
                        int endIndex = GetSegmentIndexAtColumn(startLine, terminalLine.Start + end.Column);
                        for (int i = startIndex; i <= endIndex; i++)
                        {
                            var segment = startLine.GetColorChar(i);
                            sb.Append(segment.Char);

                        }
                    }



                }

            }

            return sb.ToString();
        }

        /// <summary>
        /// 列模式 取得复制的文本,
        /// </summary>
        /// <returns></returns>
        private string GetSelectedTextALt()
        {
            if (!_selection.IsValid) return "";

            ///此参数是列模式时没有计算的中文宽带的情况下，列的索引 ，后续需要逐行处理修正
            CharPosition start = _selection.StartALT;

            CharPosition end = _selection.EndALT;
            // 确保起始列小于结束列
            if (start.Line > end.Line)
            {
                var temp = start;
                start = end;
                end = temp;
            }

            int StartCol = Math.Min(start.Column, end.Column);
            int EndCol = Math.Max(start.Column, end.Column);


            var sb = new StringBuilder();
            LineInfo terminalLine = null;
            for (int line = start.Line; line <= end.Line; line++)
            {
                if (line < 0 || line >= Count)
                {
                    continue;
                }


                if (line < _HistroylineInfo.Count)
                {
                    terminalLine = _HistroylineInfo[line];
                }
                else
                {
                    terminalLine = _CulineInfo[line - _HistroylineInfo.Count];
                }
                //根据索引 取得当前数据行实例
                var currentLine = _buffer[terminalLine.LineIndex];
                //  var sssddd=   currentLine.ToString();
                //  Console.WriteLine(sssddd);
                //   int currentColumn = 0;

                //StartCol  修正中文的情况的索引值

                ///判断改行 索引开始的位置 之前 是否存在中文，没一个中文 - 1

                var StartColTmp = StartCol;
                var EndColTmp = EndCol;
                for (int i = terminalLine.Start; i < StartCol; i++)
                {
                    if (i <= terminalLine.End)
                    {
                        var segment = currentLine.GetColorChar(i);
                        if (segment != null)
                        {
                            if (IsChinese(segment.Char))
                            {
                                StartColTmp--;
                                i++;
                            }
                        }
                    }
                }


                for (int i = StartColTmp; i <= EndColTmp; i++)
                {

                    if ((i + terminalLine.Start) <= terminalLine.End)
                    {
                        var segment = currentLine.GetColorChar(terminalLine.Start + i);
                        if (segment != null)
                        {
                            //   Console.WriteLine(terminalLine.Start + i + "==> "+ segment.Char);
                            // int charWidth = IsChinese(segment.Char) ? 2 : 1;
                            //if (currentColumn >= StartCol && currentColumn + charWidth - 1 <= EndCol)
                            //{

                            if (IsChinese(segment.Char))
                            {
                                EndColTmp--;
                            }
                            sb.Append(segment.Char);
                            //}
                            //  currentColumn += charWidth;
                        }
                        else
                        {
                            break;
                            Console.WriteLine("null:  " + terminalLine.LineIndex + " " + StartCol);
                        }

                    }
                    else
                    {
                        break;
                    }

                }
                if (line < end.Line)
                {
                    sb.AppendLine();
                }
            }
            return sb.ToString();
        }




        /// <summary>
        /// 根据行索引 取得 
        /// </summary>
        /// <param name="line"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        private int GetSegmentIndexAtColumn(TerminalLine line, int column)
        {

            if (line.Length > column)
            {
                return column;

            }
            else
            {
                return -1;
                throw new ArgumentException("索引大于实际的数组长度", nameof(column));
                // TryExpression tryExpression;
                return line.Length;

            }

        }

        ///// <summary>
        ///// 局部重绘标记
        ///// </summary>
        //bool isDirty = false;

        ///// <summary>
        ///// 互斥锁
        ///// </summary>
        //private object locket = new object();

        /// <summary>
        /// 指定区域重绘，时出现 ，当前测试，未使用
        /// </summary>
        /// <returns></returns>
        private PointF GetNextCharRectangleF()
        {

            //lock (locket)
            //{
            int lineIndex = _buffer.Count - 1;
            //  int charIndex =  _buffer[lineIndex].？Count?;
            int charIndex = _buffer[lineIndex]?.Count ?? 0;
            // int charIndex = _buffer.Last().Count;
            float xPos = Math.Max((charIndex - 1) * (int)CharWidth, 0);
            float yPos = (lineIndex * CharHeight) - _scrollOffset;
            return new PointF(xPos, yPos);

            //  }

        }

        /// <summary>
        /// 当存在最大行数限制时，使用；当前大量数据时，存在异常情况
        /// </summary>
        private void HandleScreenBuffer()
        {
            if (_HistroylineInfo.Count + _CulineInfo.Count > _maxLines)
            {
                _buffer.RemoveRange(0, _HistroylineInfo.Count + _CulineInfo.Count - _maxLines);
                _scrollOffset = Math.Max(0, _scrollOffset -
                 //   (_HistroylineInfo.Count + _CulineInfo.Count - _maxLines) * (int)_charSize.Height);
                (_HistroylineInfo.Count + _CulineInfo.Count - _maxLines) * (int)CharHeight);
            }
        }


        #region

        public void AddColorMatcher(ColorMatchRule colorMatchRule)
        {
            this.colorMatcher.AddRule(colorMatchRule);
        }


        #endregion

        #region 解析VT100 控制码

        private const byte ESC = 0x1B;
        private const byte BEL = 0x07;

        #endregion

        private List<VT100Command> VT100Parser(char[] data)
        {
            List<VT100Command> commands = new List<VT100Command>();
            VT100Command commandNormalChar = new VT100Command(VT100Action.NormalChar);

            int i = 0;

            while (i < data.Length)
            {
                if (data[i] == BEL)
                {
                    if (commandNormalChar.Count > 0)
                    {

                        commands.Add(commandNormalChar);

                        commandNormalChar = new VT100Command(VT100Action.NormalChar);
                    }
                    //响铃 /a
                    commands.Add(new VT100Command(VT100Action.Bell));
                    i++;
                }
                else if (data[i] == ESC)
                {

                    i++;
                    if (i < data.Length)
                    {
                        if (data[i] == '[')
                        {
                            if (commandNormalChar.Count > 0)
                            {

                                commands.Add(commandNormalChar);

                                commandNormalChar = new VT100Command(VT100Action.NormalChar);
                            }
                            i++;

                            //解析 控制码后面跟着的 参数
                            List<int> parameters = new List<int>();
                            int currentParam = 0;

                            // 解析参数
                            while (i < data.Length && char.IsDigit((char)data[i]))
                            {
                                currentParam = currentParam * 10 + (data[i] - '0');
                                i++;
                                if (i < data.Length && data[i] == ';')
                                {
                                    parameters.Add(currentParam);
                                    currentParam = 0;
                                    i++;
                                }
                            }
                            parameters.Add(currentParam);

                            if (i < data.Length)
                            {
                                switch (data[i])
                                {
                                    case 'A':
                                        //commandControl = new VT100Command(VT100Action.CursorUp);
                                        commands.Add(new VT100Command(VT100Action.CursorUp, parameters));
                                        break;
                                    case 'B':
                                        //  commandControl = new VT100Command(VT100Action.CursorDown);
                                        commands.Add(new VT100Command(VT100Action.CursorDown, parameters));
                                        break;
                                    case 'C':
                                        //    commandControl = new VT100Command(VT100Action.CursorRight);
                                        commands.Add(new VT100Command(VT100Action.CursorRight, parameters));
                                        break;
                                    case 'D':
                                        //  commandControl = new VT100Command(VT100Action.CursorLeft);
                                        commands.Add(new VT100Command(VT100Action.CursorLeft, parameters));
                                        break;
                                    case 'H':
                                        break;
                                    case 'f':
                                        commands.Add(new VT100Command(VT100Action.MoveToPosition, parameters));
                                        break;
                                    case 'J':
                                        commands.Add(new VT100Command(VT100Action.ClearScreen, parameters));
                                        break;
                                    case 'K':
                                        commands.Add(new VT100Command(VT100Action.ClearLine, parameters));
                                        break;
                                    case 'm':
                                        if (parameters[0] >= 30 && parameters[0] <= 37)
                                        {
                                            commands.Add(new VT100Command(VT100Action.SetForegroundColor, parameters));
                                        }
                                        else if (parameters[0] >= 40 && parameters[0] <= 47)
                                        {
                                            commands.Add(new VT100Command(VT100Action.SetBackgroundColor, parameters));
                                        }
                                        else
                                        {
                                            commands.Add(new VT100Command(VT100Action.SetTextAttribute, parameters));
                                        }
                                        break;
                                    default:
                                        // commands.Add(new VT100Command(VT100Action.Unknown));
                                        break;
                                }
                            }
                            i++;
                        }
                        else
                        {
                            //   commands.Add(new VT100Command(VT100Action.Unknown));
                            commandNormalChar.AddColorChar((char)data[i]);
                            i++;
                        }
                    }
                }
                else
                {
                    if (data[i] == '\b' || data[i] == '\u001b')
                    {
                        if (commandNormalChar.Count > 0)
                        {

                            commands.Add(commandNormalChar);

                            commandNormalChar = new VT100Command(VT100Action.NormalChar);
                        }
                        commands.Add(new VT100Command(VT100Action.Black));

                        //退格键
                    }
                    else if (data[i] == '\r')
                    {

                        //if (commandNormalChar.Count > 0)
                        //{

                        //    commands.Add(commandNormalChar);

                        //    commandNormalChar = new VT100Command(VT100Action.NormalChar);
                        //}
                        commands.Add(new VT100Command(VT100Action.CarriageReturn));
                        //// i++;
                        //if (i+1 < data.Length)
                        //{
                        //    if (data[i + 1] == '\n')
                        //    {
                        //        i++;
                        //    }
                        //}
                        //else
                        //{
                        //    break;
                        //}
                    }

                    else if (data[i] == '\n')
                    {
                        if (commandNormalChar.Count > 0)
                        {

                            commands.Add(commandNormalChar);

                            commandNormalChar = new VT100Command(VT100Action.NormalChar);
                        }
                        commands.Add(new VT100Command(VT100Action.NormanlNewLine));
                    }
                    else
                    {
                        commandNormalChar.AddColorChar((char)data[i]);

                    }

                    //else if (data[i] == '\n')
                    //{

                    //}


                    i++;

                }
            }


            if (commandNormalChar.Count > 0)
            {
                commands.Add(commandNormalChar);
            }

            return commands;
        }



        #region 右键菜单栏
        //复制
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.CopySelection();
        }
        //粘贴
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            try
            {
                if (Clipboard.ContainsText())
                {
                    string text = Clipboard.GetText();

                    this.OnInPutData(Encoding.UTF8.GetBytes(text));
                    // Console.WriteLine("从剪贴板获取的文本数据: " + text);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            //else
            //{
            //    Console.WriteLine("剪贴板中没有文本数据。");
            //}
        }
        //复制并粘贴
        private void 复制并粘贴ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!_selection.IsValid) return;

            var text = GetSelectedText();
            if (text != null)
            {
                try
                {
                    Clipboard.SetText(text);
                    this.OnInPutData(Encoding.UTF8.GetBytes(text));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        //全选
        private void 全选ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
        //查找
        private void 查找ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form_find form_Find = new Form_find(this);
            form_Find.Show();
        }

        ///// <summary>
        ///// 查找的文本索引
        ///// </summary>
        //int FindIndexLine = 0;

        /// <summary>
        /// 当前数据的行数查找的文本索引
        /// </summary>
        public int GetBufferCount => _HistroylineInfo.Count + _CulineInfo.Count - 1;

        /// <summary>
        /// 查找文本
        /// </summary>
        /// <param name="findstr"></param>
        /// <returns></returns>
        public bool FindStr(string findstr, bool IsUp, ref int FindIndexLine)
        {
            if (IsUp)
            {//向上查找
                while (FindIndexLine != -1)
                {
                    if (FindIndexLine < _HistroylineInfo.Count)
                    {
                        if (Findstr(_HistroylineInfo[FindIndexLine], FindIndexLine, findstr, IsUp))
                        {
                            return true;
                            break;
                        }
                        // DrawLine(g, _HistroylineInfo[FindIndexLine], yPos);
                    }
                    else
                    {
                        if (Findstr(_CulineInfo[FindIndexLine - _HistroylineInfo.Count], FindIndexLine, findstr, IsUp))
                        {
                            return true;
                            break;
                        }

                    }

                    FindIndexLine--;
                }
                return false;

            }
            else
            {
                //向下查找
                while (FindIndexLine < Count)
                {
                    if (FindIndexLine < _HistroylineInfo.Count)
                    {
                        if (Findstr(_HistroylineInfo[FindIndexLine], FindIndexLine, findstr, IsUp))
                        {
                            return true;
                            break;
                        }
                        // DrawLine(g, _HistroylineInfo[FindIndexLine], yPos);
                    }
                    else
                    {
                        if (Findstr(_CulineInfo[FindIndexLine - _HistroylineInfo.Count], FindIndexLine, findstr, IsUp))
                        {
                            return true;
                            break;
                        }

                    }

                    FindIndexLine++;
                }
                return false;
            }

        }

        private bool Findstr(LineInfo lineInfo, int FindIndexLine, string findstr, bool IsUp)
        {
            string rowsdata = _buffer[lineInfo.LineIndex].ToString(lineInfo.Start, lineInfo.End);
            var findindex = rowsdata.IndexOf(findstr);
            if (findindex != -1)
            {
                //匹配值
                _selection.Start = new CharPosition(lineInfo.LineIndex, findindex);
                // _buffer[lineInfo.LineIndex].GetStartOffsetIndex(lineInfo.Start, lineInfo.End);
                _selection.End = new CharPosition(lineInfo.LineIndex, findindex + findstr.Length - 1);
                _selection.IsValid = true;
            //    int startLine = _scrollOffset / (int)_charSize.Height;
                int startLine = _scrollOffset / (int)CharHeight;
                ///可见区域第一行
                //判断 查找到 行是否在可见区域
                if (FindIndexLine >= startLine)
                {
                    if (FindIndexLine <= startLine + Rows)
                    {
                        //在可见区域
                    }
                    else
                    {
                        //在可见区域的下发，向下滚动
                        ToGunDongTiaoLine(FindIndexLine, IsUp);
                    }
                }
                else
                {
                    ToGunDongTiaoLine(FindIndexLine, IsUp);
                }
                TriggerRefresh();


                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="lineindex">行的索引</param>
        /// <param name="IsUp">滚动方向，是否向上</param>
        private void ToGunDongTiaoLine(int lineindex, bool IsUp)
        {

            if (IsUp)
            {
                var firstline = _scrollOffset / (int)CharHeight;
                if (lineindex > (firstline + Rows))
                {
                    _scrollOffset = (lineindex - Rows + 1) * (int)CharHeight;
                }
                else
                {//在行首显示
                    _scrollOffset = (lineindex) * (int)CharHeight;
                }

            }
            else
            {
                if (lineindex > Rows)
                {
                    _scrollOffset = (lineindex - Rows + 1) * (int)CharHeight;
                }
                else
                {
                    _scrollOffset = (lineindex) * (int)CharHeight;
                }
            }



            UpdateScrollBars(_scrollOffset);
        }

        #endregion













    }
    #endregion

    #region 数据结构
    public class TerminalLine
    {

        public int HistroyLineInfoStartIndex = 0;
        public TerminalLine()
        {
            IsCursor = true;
        }
        /// <summary>
        /// 光标索引
        /// </summary>
        public int Index { get; private set; }
        private List<ColorChar> Segments { get; } = new List<ColorChar>();

        /// <summary>
        /// GetColorChar
        /// </summary>
        /// <param name="CharIndex"></param>
        /// <returns></returns>
        public ColorChar GetColorChar(int CharIndex)
        {
            if (Segments.Count > CharIndex && CharIndex >= 0)
            {
                return Segments[CharIndex];
            }
            else
            {
                return null;
            }

        }
        /// <summary>
        /// 计算存在中文时的 实际索引
        /// </summary>
        /// <returns></returns>
        public int GetStartOffsetIndex(int ChaIndex)
        {
            int Line = Math.Min(ChaIndex, this.Count);
            int off = 0;
            for (int i = 0; i < Line; i++)
            {
                if (IsChinese(Segments[i].Char))
                {
                    off += 2;
                }
                else
                {
                    off++;
                }
            }
            return off;

        }        /// <summary>
                 /// 计算存在中文时的 实际索引
                 /// </summary>
                 /// <returns></returns>
        public int GetStartOffsetIndex(int start, int end)
        {
            int Line = Math.Min(end, this.Count);
            int off = 0;
            for (int i = start; i < Line; i++)
            {
                if (IsChinese(Segments[i].Char))
                {
                    off += 2;
                }
                else
                {
                    off++;
                }
            }
            return off;

        }


        /// <summary>
        /// 取得计算中文后的索引， 中文 的 * 2
        /// </summary>
        /// <returns></returns>
        private int GetLengthSum()
        {
            int off = 0;
            for (int i = 0; i < this.Count; i++)
            {
                if (IsChinese(Segments[i].Char))
                {
                    off += 2;
                }
                else
                {
                    off++;
                }
            }
            return off;
        }
        /// <summary>
        /// 判断字符是否为中文
        /// </summary>
        /// <param name="c">字符</param>
        /// <returns>是否为中文</returns>
        private bool IsChinese(char c)
        {
            return c >= '\u4E00' && c <= '\u9FFF';
        }
        /// <summary>
        /// 删除光标索引到行的末尾的所有数据
        /// </summary>
        public void ClearLine()
        {
            try
            {
                if (Count > Index)
                {
                    Segments.RemoveRange(Index, Count - Index);
                }
                //while (Count > Index)
                //{
                //    Segments.RemoveAt(Count - 1);
                //}
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


        }
        /// <summary>
        /// 宽度 与 Count 一致
        /// </summary>
        public int Length => Segments.Count;

        /// <summary>
        /// 计数
        /// </summary>
        public int Count => Segments.Count;

        /// <summary>
        /// 更新颜色
        /// </summary>
        /// <param name="Index1"></param>
        /// <param name="color"></param>
        public void UpdataColor(int Index1, Color color)
        {
            if (Index1 >= 0 && Index1 < Count)
            {
                Segments[Index1].CharColor = color;
            }

        }

        /// <summary>
        /// 光标左移
        /// </summary>
        /// <param name="num"></param>
        public void CursorLeft(int num)
        {
            Index = Math.Max(Index - num, 0);
        }
        /// <summary>
        /// 光标右移
        /// </summary>
        /// <param name="num"></param>
        public void CursorRight(int num)
        {
            Index = Math.Min(Index + num, Count);
        }
        /// <summary>
        /// 光标左移动到行首位位置
        /// </summary>
        public void CarriageReturn()
        {
            Index = 0;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public List<ColorChar> GetSegments()
        {
            return Segments.ToList();
        }
        public void Add(ColorChar colorChar)
        {
            if (colorChar.Char == '\a')
            {
                return;
            }

            Segments.Insert(Index++, colorChar);

        }

        /// <summary>
        /// 插入大量colorChar
        /// </summary>
        /// <param name="colorChar"></param>
        public void AddRange(List<ColorChar> colorChar)
        {      // 先检查索引是否合法
            if (Index < 0 || Index > Segments.Count)
            {
                throw new ArgumentException("索引超出有效范围。", nameof(Index));
            }
            //Segments.InsertRange(Index, colorChar);

            //Index += colorChar.Count;
            int startIndex = Index;
            int endIndex = Math.Min(startIndex + colorChar.Count, Segments.Count);

            // 覆盖现有元素
            for (int i = 0; i < endIndex - startIndex; i++)
            {
                Segments[startIndex + i] = colorChar[i];
            }

            // 如果 colorChar 列表长度超过 Segments 剩余空间，添加剩余元素
            if (colorChar.Count > endIndex - startIndex)
            {
                int remainingCount = colorChar.Count - (endIndex - startIndex);
                for (int i = 0; i < remainingCount; i++)
                {
                    Segments.Add(colorChar[endIndex - startIndex + i]);
                }
            }
            Index = startIndex + colorChar.Count;
        }

        public void Remote()
        {
            if (Index > 0)
            {
                Segments.RemoveAt(--Index);
            }

        }

        /// <summary>
        /// 光标是否在本行显示，
        /// </summary>
        public bool IsCursor = false;



        /// <summary>
        /// 取得当前行的 List<LineInfo>
        /// </summary>
        /// <param name="TerminalLineIndex"></param>
        /// <param name="Cols"></param>
        /// <returns></returns>
        public List<LineInfo> GetCuLineInfo(int TerminalLineIndex, int Cols)
        {
            List<LineInfo> infos = new List<LineInfo>();
            // int length = this.GetLengthSum();
            int length = this.Count;

            int Rows = length / Cols;
            int yushu = length % Cols;

            if (Rows == 0)
            {//一行以内
                infos.Add(new LineInfo(TerminalLineIndex)
                {
                    Start = 0,
                    End = length
                });
            }
            else if (Rows == 1 && yushu == 0)
            {//正好一行
                infos.Add(new LineInfo(TerminalLineIndex)
                {
                    Start = 0,
                    End = length
                });
            }
            else if (yushu == 0)
            {
                //多行整行

                for (int i = 0; i < Rows; i++)
                {
                    infos.Add(new LineInfo(TerminalLineIndex)
                    {
                        Start = Cols * i,
                        End = Cols * (1 + i),
                    });
                }

            }
            else
            {
                //多行且不整行

                for (int i = 0; i < Rows; i++)
                {
                    infos.Add(new LineInfo(TerminalLineIndex)
                    {
                        Start = 0 + Cols * i,
                        End = 0 + Cols * (1 + i),
                    });
                }
                infos.Add(new LineInfo(TerminalLineIndex)
                {
                    Start = 0 + Cols * Rows,
                    End = length,
                });

            }

            return infos;
        }
        public override string ToString()
        {
            var sb = new StringBuilder();
            foreach (ColorChar colorChar in Segments)
            {
                sb.Append(colorChar);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 按索引取得范围的文本
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public string ToString(int start, int end)
        {
            var sb = new StringBuilder();
            var ends = Math.Min(Count, end);
            for (int i = start; i < ends; i++)
            {
                sb.Append(Segments[i]);

            }
            Console.WriteLine(sb.ToString());
            return sb.ToString();
        }
        /// <summary>
        /// 重置颜色
        /// </summary>
        public void RestColor()
        {
            foreach (ColorChar colorChar in Segments)
            {
                colorChar.CharColor = VirtualTerminal.DefaultForeColor;
            }
        }
    }

    /// <summary>
    /// 屏幕打印信息
    /// </summary>
    public class LineInfo : IComparable<LineInfo>
    {
        /// <summary>
        /// 行号索引 与 TerminalLine 一一对应
        /// </summary>
        public int LineIndex { get; private set; }

        /// <summary>
        /// 实例化  设置行号索引 与 宽度
        /// </summary>
        /// <param name="LineIndex"></param>
        public LineInfo(int LineIndex)
        {
            this.LineIndex = LineIndex;
        }
        public int CompareTo(LineInfo other)
        {
            return LineIndex.CompareTo(other.LineIndex);
        }


        /// <summary>
        /// 长度计数
        /// </summary>

        public int Count => End - Start;
        /// <summary>
        /// 是否存在光标
        /// </summary>
        public bool IsCursor = false;

        /// <summary>
        /// 光标索引位置
        /// </summary>
        public int Index = 0;
        ///// <summary>
        ///// 更新Start
        ///// </summary>
        ///// <param name="Start"></param>
        //public void SetStart(int Start)
        //{
        //    this.Start = Start;
        //}

        ///// <summary>
        ///// 更新End
        ///// </summary>
        ///// <param name="End"></param>
        //public void SetEnd(int End)
        //{
        //    this.End = End;
        //}
        public int Start { get; set; }
        public int End { get; set; }

    }


    public class ColorChar : ICloneable
    {
        /// <summary>
        /// 字符
        /// </summary>
        public char Char;

        /// <summary>
        /// 设置选中状态
        /// </summary>
        public bool _IsCheckedState = false;
        /// <summary>
        /// 选中状态
        /// </summary>
        public bool IsCheckedState
        {
            get { return _IsCheckedState; }
            private set { _IsCheckedState = value; }
        }


        /// <summary>
        /// 设置选中状态
        /// </summary>
        public void SelectedCheckedState()
        {
            IsCheckedState = true;

        }

        /// <summary>
        /// 取消选中状态
        /// </summary>
        public void UnSelectedCheckedState()
        {
            IsCheckedState = false;

        }
        /// <summary>
        /// 实例化
        /// </summary>
        /// <param name="cha">初始字符</param>
        /// <param name="IsCheckedState"></param>
        public ColorChar(char cha, Color color, bool IsCheckedState)
        {
            this.Char = cha;
            this.CharColor = color;
            this.IsCheckedState = IsCheckedState;
            this.CharColor = VirtualTerminal.DefaultForeColor;
        }
        /// <summary>
        /// 实例化
        /// </summary>
        /// <param name="cha">初始字符</param>
        /// <param name="IsCheckedState"></param>
        public ColorChar(char cha, bool IsCheckedState)
        {
            this.Char = cha;
            this.IsCheckedState = IsCheckedState;
            this.CharColor = VirtualTerminal.DefaultForeColor;
        }
        public ColorChar(bool IsCheckedState)
        {
            this.IsCheckedState = IsCheckedState;
        }
        /// <summary>
        /// 构造函数迭代
        /// </summary>
        /// <param name="cha"></param>
        public ColorChar(char cha) : this(cha, false)
        { }


        /// <summary>
        /// 初始化
        /// </summary>
        public ColorChar() : this(false)
        { }


        /// <summary>
        /// 创建初始字符实例状态
        /// </summary>
        /// <param name="cha"></param>
        /// <returns></returns>
        public static ColorChar CreatColorChar(char cha)
        {
            //  ColorChar colorChar = new ColorChar(cha);
            return new ColorChar(cha);
        }


        /// <summary>
        ///  字符串 转 List<ColorChar>
        /// </summary>
        /// <param name="rows"></param>
        /// <returns></returns>
        public static List<ColorChar> GreatCharFormRows(string rows)
        {
            List<ColorChar> list = new List<ColorChar>();
            if (rows.Length == 0)
            {
                return list;
            }

            foreach (char ch in rows)
            {
                list.Add(new ColorChar(ch));

            }
            return list;
        }

        public override string ToString()
        {
            return Char.ToString();
        }
        public Color CharColor { get; set; }

        /// <summary>
        /// 创建一个浅副本对象
        /// </summary>
        /// <returns></returns>
        public object Clone()
        {
            return this.MemberwiseClone();

        }


        /// <summary>
        /// 创建克隆实例
        /// </summary>
        /// <returns></returns>
        public ColorChar GetClone()
        {
            return (ColorChar)MemberwiseClone();
        }
    }


    struct CharPosition
    {
        public int Line { get; }
        public int Column { get; }

        //public Point PointStart { get; }
        //public Point PointEnd { get; }
        public CharPosition(int line, int column)
        {
            Line = line;
            Column = column;
        }
        //public CharPosition(int line, int column, Point Start, Point EndPot)
        //{
        //    Line = line;
        //    Column = column;
        //    this.PointStart = Start;
        //    this.PointEnd = EndPot;
        //}
        //public override string ToString()
        //{
        //    return "Line: " + Line + " Column: " + Column;
        //}
    }



    class Selection
    {
        /// <summary>
        /// 开始的节点
        /// </summary>
        public Point StartPoint { get; set; }

        /// <summary>
        /// 终止的节点
        /// </summary>
        public Point EndPoint { get; set; }
        public CharPosition Start { get; set; }
        public CharPosition StartALT { get; set; }
        public CharPosition End { get; set; }
        public CharPosition EndALT { get; set; }
        public bool IsValid = false;

        /// <summary>
        /// 历史选中区域否为列模式
        /// </summary>
        public bool IsAltDown = false;
        //  public bool IsValid => Start.Line != End.Line;
        //public bool IsValid => Start.Line != End.Line || Start.Column != End.Column;
    }
    #endregion
    #region //VT100控制编码 处理

    public enum VT100Action
    {
        CursorUp,
        CursorDown,
        CursorRight,
        CursorLeft,
        MoveToPosition,
        ClearScreen,
        ClearLine,//清除到行尾的数据
        SetTextAttribute,
        SetForegroundColor,
        SetBackgroundColor,
        Bell,
        NormalChar, //普通字符串
        NormanlNewLine, //换行
        Black,//退格键 Backspace

        /// <summary>
        /// 移动到行首位
        /// </summary>
        CarriageReturn,//移动到行首位
    }


    // 辅助结构体，用于存储解析后的 VT100 信息
    public class VT100Command
    {
        public VT100Action Action;
        public List<int> Parameters;
        public List<ColorChar> colorChars = new List<ColorChar>();
        public int Count => colorChars.Count;

        public VT100Command(VT100Action action)
        {
            Action = action;
        }
        public VT100Command(VT100Action action, List<int> parameters)
        {
            Action = action;
            this.Parameters = parameters;
        }
        public VT100Command(VT100Action action, string parameters)
        {
            Action = action;
            Console.WriteLine(parameters);
        }
        public void AddColorChar(char ch)
        {
            AddColorChar(ch, VirtualTerminal.DefaultForeColor);
        }
        public void AddColorChar(char ch, Color color)
        {
            colorChars.Add(new ColorChar(ch, color, false));
        }
        public void AddColorChar(ColorChar colorChar)
        {
            colorChars.Add(colorChar);
        }

    }
    #endregion

    #region

    public class ScrollbarTime : System.Timers.Timer
    {
        // CustomElapsedEventArgs

        public EvenGlineInfrom glineInfrom;

        public delegate void ScrollbarTimeEventHandler(object sender, EvenGlineInfrom e);
        public void Start(EvenGlineInfrom evenGlineInfrom)
        {
            this.glineInfrom = evenGlineInfrom;
            base.Start();
        }
        public ScrollbarTime(int time)
        {
            base.Interval = time;
        }

    }
    public class EvenGlineInfrom : EventArgs
    {
        public delegate void EvenGlineInfromEventHandler(object sender, EvenGlineInfrom e);
        public int MaxLineNum { get; private set; }
        public int CuLineNum { get; private set; }
        public EvenGlineInfrom(int MaxLineNum, int CuLineNum)
        {
            this.CuLineNum = CuLineNum;
            this.MaxLineNum = MaxLineNum;
        }
    }

    #endregion


    #region //字体关键字颜色处理
    // 表示一个字符范围的类
    public class CharRange
    {
        public int Start { get; set; }
        public int End { get; set; }
        public CharRange(int start, int end)
        {
            Start = start;
            End = end;
        }
        public bool IsEmpty => Start >= End;
    }
    // 颜色匹配规则类

    /// <summary>
    /// 颜色匹配规则类
    /// </summary>
    public class ColorMatchRule
    {
        public Regex Pattern { get; set; }
        public Color Color { get; set; }

        public ColorMatchRule(string pattern, Color color)
        {
            Pattern = new Regex(pattern);

            Color = color;
        }
    }
    // 颜色匹配器类
    public class ColorMatcher
    {



        /// <summary>
        /// 规则数
        /// </summary>
        public int Count => rules.Count;
        private List<ColorMatchRule> rules = new List<ColorMatchRule>();

        // 添加匹配规则
        public void AddRule(string pattern, Color color)
        {
            AddRule(new ColorMatchRule(pattern, color));
        }

        public void AddRule(ColorMatchRule colorMatchRule)
        {
            rules.Add(colorMatchRule);
        }


        // 更新 TerminalLine 中字符的颜色
        // 更新 TerminalLine 中字符的颜色
        public bool UpdataColorChar(TerminalLine terminalLine)
        {
            if (terminalLine == null || terminalLine.Count == 0)
            {
                return false;
            }
            string lineText = terminalLine.ToString();

            //  Console.WriteLine("原始文本信息：===> 开始" + lineText);
            // 初始范围为整个文本
            List<CharRange> availableRanges = new List<CharRange> { new CharRange(0, lineText.Length) };
            int StartIndex = 1;
            foreach (var rule in rules)
            {

                //  Console.WriteLine("开始=======匹配 rule：[ "+ StartIndex + " ]=====》 正则表达式规则："+ rule.Pattern.ToString());
                List<CharRange> newAvailableRanges = new List<CharRange>();
                // Console.WriteLine("availableRanges:Count: "+ availableRanges.Count);
                foreach (var range in availableRanges)
                {
                    //  newAvailableRanges.Clear();


                    // Match match11 = rule.Pattern.Match(lineText, range.Start, range.End - range.Start);
                    MatchCollection matches1 = rule.Pattern.Matches(lineText, range.Start);
                    if (matches1.Count > 0)
                    {
                        foreach (Match match in matches1)
                        {

                            //     Console.WriteLine($"匹配内容: {match.Value}, 起始位置: {match.Index}  {match.Length}");
                            // 输出匹配到的子字符串及其在输入字符串中的起始位置
                            // 处理匹配前的范围

                            if (match.Success && match.Length > 0)
                            {
                                if (match.Index > range.Start)
                                {
                                    //  newAvailableRanges.Add(new CharRange(range.Start, match.Index));
                                }
                                //     Console.WriteLine("找到以下匹配结果：" + match.Value);
                                // 更新匹配字符的颜色
                                for (int i = match.Index; i < match.Index + match.Length; i++)
                                {
                                    terminalLine.UpdataColor(i, rule.Color);
                                }
                                //     currentIndex = match.Index + match.Length;
                            }
                            //   else if (match.Success)
                            //   {
                            //       Console.WriteLine("匹配内容: match.length ==0");
                            ////       currentIndex = match.Index + match.Length;
                            //   }


                        }
                    }


                    //int currentIndex = range.Start;
                    //int LastIndex = range.Start;
                    //while (currentIndex < range.End)
                    //{
                    //    MatchCollection matches = rule.Pattern.Matches(lineText, currentIndex);
                    //    Console.WriteLine("匹配册数：" + matches.Count + " 匹配内容:  " + lineText);
                    //    Console.WriteLine();
                    //    if (matches.Count > 0)
                    //    {

                    //        //Console.WriteLine("找到以下匹配结果："+ );
                    //        // 遍历匹配结果集合
                    //        foreach (Match match in matches)
                    //        {

                    //            Console.WriteLine($"匹配内容: {match.Value}, 起始位置: {match.Index}  {match.Length}");
                    //            // 输出匹配到的子字符串及其在输入字符串中的起始位置
                    //            // 处理匹配前的范围
                    //            if (match.Index > currentIndex)
                    //            {
                    //                newAvailableRanges.Add(new CharRange(currentIndex, match.Index));
                    //            }
                    //            if (match.Success && match.Length > 0)
                    //            {

                    //                Console.WriteLine("找到以下匹配结果："+match.Value);
                    //                // 更新匹配字符的颜色
                    //                for (int i = match.Index; i < match.Index + match.Length; i++)
                    //                {
                    //                    terminalLine.UpdataColor(i, rule.Color);
                    //                }
                    //                currentIndex = match.Index + match.Length;
                    //            }
                    //            else 
                    //            {
                    //                currentIndex = match.Index + match.Length;
                    //            }


                    //        }



                    //    }
                    //    else
                    //    {                            // 剩余部分作为新的可用范围
                    //        if (LastIndex != currentIndex)
                    //        {
                    //            currentIndex += range.End;
                    //            newAvailableRanges.Add(new CharRange(currentIndex, range.End));
                    //        }

                    //        break;
                    //        Console.WriteLine("未找到匹配结果。");
                    //    }
                    //   }


                    //Match match = rule.Pattern.Match(lineText, currentIndex, range.End - currentIndex);
                    //if (match.Success&& match.Length>0)
                    //{
                    //    Console.WriteLine("match: " + match.Length);
                    //    // 处理匹配前的范围
                    //    if (match.Index > currentIndex)
                    //    {
                    //        newAvailableRanges.Add(new CharRange(currentIndex, match.Index));
                    //    }
                    //    // 更新匹配字符的颜色
                    //    for (int i = match.Index; i < match.Index + match.Length; i++)
                    //    {
                    //        terminalLine.UpdataColor(i, rule.Color);
                    //    }
                    //    // 更新当前索引
                    //    currentIndex = match.Index + match.Length;
                    //}
                    //else
                    //{
                    //    // 剩余部分作为新的可用范围
                    //    if(LastIndex!= currentIndex)
                    //    {
                    //        currentIndex += range.End;
                    //        newAvailableRanges.Add(new CharRange(currentIndex, range.End));
                    //    }

                    //    break;
                    //}
                    //  }
                    //availableRanges = newAvailableRanges;
                }
                // 更新可用范围列表

                //  Console.WriteLine("完成============》 正则表达式规则：" + rule.Pattern.ToString());
                //   Console.WriteLine();
                //   Console.WriteLine("**************************");
                //   Console.WriteLine();
                StartIndex++;
            }

            //  Console.WriteLine("原始文本信息：===> 完成" + lineText);
            //  Console.WriteLine();
            //   Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++");
            //   Console.WriteLine();
            return true;
        }
        // 执行颜色匹配
        //public List<(string Text, Color Color)> Match(string input)
        //{
        //    List<(string Text, Color Color)> result = new List<(string Text, Color Color)>();
        //    int currentIndex = 0;

        //    while (currentIndex < input.Length)
        //    {
        //        bool matched = false;
        //        foreach (var rule in rules)
        //        {
        //            Match match = rule.Pattern.Match(input, currentIndex);
        //            if (match.Success && match.Index == currentIndex)
        //            {
        //                // 处理匹配前的文本
        //                if (match.Index > currentIndex)
        //                {
        //                    result.Add((input.Substring(currentIndex, match.Index - currentIndex), Color.Black));
        //                }
        //                // 处理匹配的文本
        //                result.Add((match.Value, rule.Color));
        //                currentIndex = match.Index + match.Length;
        //                matched = true;
        //                break;
        //            }
        //        }

        //        if (!matched)
        //        {
        //            // 没有匹配到，处理当前字符
        //            result.Add((input.Substring(currentIndex, 1), Color.Black));
        //            currentIndex++;
        //        }
        //    }

        //    return result;
        //}
    }


    #endregion
}